A list holds many values in order
marks = [78, 91, 65, 88]
names = ["Asha", "Ravi", "Meena"]
mixed = ["Asha", 15, True, 91.5] # different types are allowed
empty = []
Lists use square brackets. Items keep their order and duplicates are allowed. Indexing and slicing work exactly as they do for strings:
print(marks[0]) # 78
print(marks[-1]) # 88
print(marks[1:3]) # [91, 65]
print(len(marks)) # 4
Lists are mutable
Unlike strings, you can change a list in place:
marks[2] = 70
print(marks) # [78, 91, 70, 88]
Adding and removing items
| Method | What it does | Example |
|---|---|---|
append(x) | add x at the end | names.append("Kiran") |
insert(i, x) | add x at position i | names.insert(0, "Zoya") |
extend(list) | add every item of another list | names.extend(["A", "B"]) |
remove(x) | remove the first x (error if missing) | names.remove("Ravi") |
pop() | remove and return the last item | last = names.pop() |
pop(i) | remove and return the item at i | first = names.pop(0) |
clear() | remove everything | names.clear() |
del names[1] also removes the item at position 1.
Sorting, searching and counting
nums = [40, 10, 30, 10]
nums.sort() # changes nums: [10, 10, 30, 40]
nums.sort(reverse=True) # [40, 30, 10, 10]
ordered = sorted(nums) # a new sorted list; nums is unchanged
nums.reverse() # reverse in place
print(30 in nums) # True
print(nums.index(30)) # position of the first 30
print(nums.count(10)) # 2
print(sum(nums), max(nums), min(nums))
list.sort() returns None, so nums = nums.sort() loses your list. Use sorted() when you need a new list.
Looping over a list
marks = [78, 91, 65, 88, 42]
total = 0
for m in marks:
total += m
print("Average:", total / len(marks))
passed = []
for m in marks:
if m >= 50:
passed.append(m)
print(passed) # [78, 91, 65, 88]
When you need the position too, use enumerate():
for i, name in enumerate(["Asha", "Ravi"], start=1):
print(i, name)
Finding the topper without max()
marks = [78, 91, 65, 88]
best = marks[0]
for m in marks:
if m > best:
best = m
print(best) # 91
This "keep the best so far" idea is used everywhere, from leaderboards to finding the cheapest price.
Lists of lists (2D lists)
A list can hold other lists, which gives you rows and columns like a table:
seats = [
["Asha", "Ravi", "Meena"],
["Kiran", "Zoya", "Amit"],
]
print(seats[1][2]) # row 1, column 2: Amit
for row in seats:
for name in row:
print(name, end=" ")
print()
Copying lists: b = a does NOT make a copy
a = [1, 2, 3]
b = a # b is another name for the SAME list
b.append(4)
print(a) # [1, 2, 3, 4] -- a changed too!
c = a.copy() # a real copy (a[:] or list(a) also work)
c.append(5)
print(a) # [1, 2, 3, 4] -- unchanged
Example: shopping cart
cart = []
while True:
item = input("Add item (or 'done'): ")
if item == "done":
break
cart.append(item)
print("You bought", len(cart), "items:", ", ".join(cart))
Common mistakes
IndexErrorfrom usinglen(list)as an index: the last index islen(list) - 1.- Writing
nums = nums.sort(), which setsnumstoNone. - Expecting
b = ato copy a list. - Removing items from a list while looping over the same list.
Key points
- Lists are ordered, changeable and allow duplicates.
append,insertandextendadd;remove,popanddeltake away.sort()changes the list;sorted()returns a new one.list[row][col]reads a 2D list;copy()makes a real copy.
Practice questions
1. After x = [5, 8, 2] and x.insert(1, 9), what is x?
[5, 9, 8, 2].
2. Remove all duplicates from a list while keeping the order.
nums = [3, 1, 3, 2, 1]
unique = []
for n in nums:
if n not in unique:
unique.append(n)
print(unique) # [3, 1, 2]3. What is the difference between remove(5) and pop(5)?
remove(5) deletes the first item whose value is 5. pop(5) deletes and returns the item at position 5.
4. Find the second largest number in [45, 12, 89, 67].
nums = sorted([45, 12, 89, 67])
print(nums[-2]) # 675. Print the total of each row of [[1, 2, 3], [4, 5, 6]].
for row in [[1, 2, 3], [4, 5, 6]]:
print(sum(row)) # 6, then 15