Lists
In short
A list is an ordered, changeable collection written with square brackets, like [3, 1, 2]. You read items by position (items[0]), add with .append(), remove with .remove() or .pop(), and sort with .sort() or sorted(). Lists can hold any type, even other lists.
Creating and reading lists
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(fruits[0])
print(fruits[-1])
print(fruits[1:])
print(len(fruits))Output
['apple', 'banana', 'cherry'] apple cherry ['banana', 'cherry'] 3
Indexing and slicing work exactly like strings: positions start at 0, and negative positions count from the end.
Changing a list
tasks = ["email", "report"]
tasks.append("meeting") # add to the end
tasks.insert(0, "coffee") # add at a position
tasks.extend(["gym", "read"]) # add several
print(tasks)
tasks.remove("gym") # remove by value
last = tasks.pop() # remove and return the last item
print(last)
tasks[1] = "inbox zero" # replace by position
print(tasks)Output
['coffee', 'email', 'report', 'meeting', 'gym', 'read'] read ['coffee', 'inbox zero', 'report', 'meeting']
Sorting
scores = [72, 95, 58, 88]
print(sorted(scores)) # new sorted list
print(scores) # original unchanged
scores.sort(reverse=True) # sorts in place
print(scores)
names = ["bob", "Alice", "carol"]
print(sorted(names, key=str.lower))Output
[58, 72, 88, 95] [72, 95, 58, 88] [95, 88, 72, 58] ['Alice', 'bob', 'carol']
Useful checks and totals
prices = [4.5, 12.0, 3.25]
print(12.0 in prices)
print(sum(prices), min(prices), max(prices))
print(prices.index(3.25))
print(["a", "b", "a"].count("a"))Output
True 19.75 3.25 12.0 2 2
Lists inside lists
grid = [
[1, 2, 3],
[4, 5, 6],
]
print(grid[1][2])
print(len(grid), len(grid[0]))Output
6 2 3
The copy trap
a = [1, 2, 3]
b = a # NOT a copy: both names point to the same list
b.append(4)
print(a)
c = a.copy() # a real copy (a[:] also works)
c.append(5)
print(a)
print(c)Output
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5]
Practice
Start with cart = ["milk", "bread"]. Add "eggs" at the end, put "coffee" at the front, remove "bread", then print the cart sorted alphabetically and, on a second line, how many items it has.
Expected output:
['coffee', 'eggs', 'milk'] 3