CSCI 127 Joy and Beauty of Data · Unit 2: Data structures · on Exam 2
2.1 Lists
Study notes for Lists in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in Mathub.
Big ideas
- A list holds items in order:
scores = [90, 85, 77]. Index and slice like strings, but lists are mutable:scores[0] = 95changes it in place. - Growing and shrinking:
append(x),insert(i, x),remove(x)(first match),pop()(last item, returned) orpop(i).len, sum, min, max, sortedwork on lists. lst.sort()sorts in place and returns None;sorted(lst)returns a new sorted list and leaves the original alone. Same withreverse()versuslst[::-1].- Two names can share one list (
b = a). To copy, usea[:]orlist(a). Passing a list to a function lets the function change it. - Lists of lists make tables:
grid[row][col].text.split()turns a string into a list of words;" ".join(lst)goes back.
Code you should know
Building and changing a list
nums = [4, 1, 7]
nums.append(10)
nums.insert(0, 99)
print(nums, len(nums))
last = nums.pop()
nums.remove(1)
print(nums, last)
print(nums[1:3], nums[-1], 7 in nums)
print(sum(nums), max(nums), sorted(nums), nums)Output
[99, 4, 1, 7, 10] 5 [99, 4, 7] 10 [4, 7] 7 True 110 99 [4, 7, 99] [99, 4, 7]
sort versus sorted, and aliasing
a = [3, 1, 2]
b = a
c = a[:]
a.sort()
print(a, b, c)
result = a.sort()
print(result)
print(sorted(c, reverse=True), c)Output
[1, 2, 3] [1, 2, 3] [3, 1, 2] None [3, 2, 1] [3, 1, 2]
Averages and a list of lists
grades = [88, 92, 79, 95]
print(f"average {sum(grades) / len(grades):.1f}")
table = [[1, 2, 3], [4, 5, 6]]
print(table[1][2], len(table), len(table[0]))
for row in table:
print(sum(row))
words = "the quick brown fox".split()
print(words[-1], "_".join(words))Output
average 88.5 6 2 3 6 15 fox the_quick_brown_fox
Worked example
What does this print?
a = [5, 3, 8] b = a b.append(1) a.sort() print(a, b, a is b)
Show the solution
[1, 3, 5, 8] [1, 3, 5, 8] True. b = a makes a second name for the same list, so appending through b and sorting through a both change the one list.Common mistakes
lst = lst.sort()throws away the list (sort returns None).- Removing items from a list while looping over it skips elements.
- Confusing
append([4, 5])(adds one item, a list) withextend([4, 5])(adds two items). - Expecting
b = ato copy.
Exam tipExam questions love
pop, insert and aliasing. Track the list after every statement, and remember which methods return None.Keep going in Mathub
Mathub is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.