Module 2: Lists, dictionaries and files · 10 min
Lists
A list holds many items in order. You can add, remove and change items.
scores = [72, 85, 90]
scores.append(64)
print(scores) # [72, 85, 90, 64]
print(scores[0]) # 72
print(scores[-1]) # 64 (last item)
print(len(scores)) # 4
print(sum(scores) / len(scores)) # average
print(sorted(scores)) # [64, 72, 85, 90]
A list comprehension builds a new list in one line:
passed = [s for s in scores if s >= 70]
print(passed) # [72, 85, 90]
A slice takes a part of a list: scores[1:3] gives the items at positions 1 and 2.