MathubLearn / Practice / Excel
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

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

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.