Lists
nums = [4, 8, 15]A list keeps items in order, each at an index.
1Level 1 · BasicsBasics
So far each variable has held one value. A list holds many values in order: all the marks in a class, every item in a cart. Lists are probably the data structure you'll use most.
Making a list
marks = [78, 91, 65, 88] names = ["Rafi", "Sara", "Tuhin"] empty = []
Lists use square brackets, with commas between items. A list can hold any types, even mixed, though usually all items are the same kind.
Indexing and slicing work just like strings
marks[0] # 78 (first) marks[-1] # 88 (last) marks[1:3] # [91, 65] len(marks) # 4
Lists can change
Unlike strings, lists are mutable, so you can change them in place:
| Code | What it does |
|---|---|
marks[0] = 80 | replace an item |
marks.append(70) | add to the end |
marks.insert(1, 99) | insert at position 1 |
marks.remove(65) | remove the first 65 |
marks.pop() | remove and return the last item |
marks.sort(), marks.reverse() | sort / reverse in place |
Handy functions
sum(marks), max(marks), min(marks) and len(marks) do what they say. sorted(marks) returns a new sorted list and leaves the original alone. 70 in marks checks membership.
Looping over a list
for m in marks:
print(m)
for i, m in enumerate(marks): # index and value together
print(i, m)
Reading a list from input
Many problems give numbers on one line. This line turns "4 8 15" into [4, 8, 15]:
nums = list(map(int, input().split()))
Key points: lists are ordered and changeable; index from 0;append()adds;sort()changes the list butsorted()makes a new one;sum,max,min,lenwork on lists.
See it in actionA list is a row of numbered boxes
Watch boxes being added, replaced, sorted and removed.
Try it yourselfExample 1: Basic list operations
Each operation changes the list. Watch it grow and get sorted.
Output appears hereAdd and count
Fill the blanks so mango is added to the end of the list and the program prints 3.
fruits = ["apple", "banana"] fruits.("mango") print((fruits))
The last item
This should print the last score, 91, but it crashes. Fix it.
Example 2: Class average
sum() and len() give the average; a loop finds who scored above it.
Output appears hereClass average
Fill the blanks so the program prints the average mark, 80.0.
marks = [70, 80, 90] print((marks) / (marks))
Example 3: Read numbers from input
Change the numbers in the Input box.
Output appears hereHighest and lowest
Read numbers on one line (like 4 9 1 7) and print the highest and lowest: Max: 9 Min: 1.
Example input4 9 1 7Expected outputMax: 9 Min: 1
Example 4: enumerate and building a new list
enumerate() gives position and value; append() builds a list of results.
Output appears hereKeep the even numbers
Read numbers on one line and print a list of only the even ones, like [4, 2, 8] for 4 7 2 9 8.
Example input4 7 2 9 8Expected output[4, 2, 8]
2Level 2 · IntermediateSorting, searching and lists of lists
sort() vs sorted()
items.sort() changes the list itself and returns None; sorted(items) returns a new list. Both take reverse=True and a key, e.g. sorted(words, key=len).
Finding things
x in items, items.index(x) and items.count(x). index raises an error if x isn't there, so check with in first.
2-D lists (grids)
A list of lists is a table: grid[row][col]. Create it with a loop that appends a fresh row each time: for _ in range(3): grid.append([0] * 3). Never use [[0] * 3] * 3: that repeats the same inner list three times.
See it in actionThe [[0]*3]*3 trap
Watch how changing one cell of bad changes a whole column, while good changes one cell.
Example 5: Sorting with a key
The key decides what to compare. Lists compare item by item, so putting the mark first sorts the students by mark.
Output appears hereExample 6: A grid of seats
Book a few seats, then print the hall. Row and column numbers start at 0.
Output appears here3Level 3 · AdvancedCopies, performance and the right tool
Shallow vs deep copy
a.copy() or a[:] copies the outer list only; inner lists are shared. To copy everything, copy each inner list too. (The copy module, which you'll meet in the Modules lesson, has deepcopy() for this.)
What's fast and what's slow
Adding or removing at the end (append, pop()) is instant. Inserting or removing at the front (insert(0, x), pop(0)) shifts every item. x in list checks items one by one.
Stacks and queues
A list with append() and pop() is a stack: the last item in is the first out, like a browser's Back button. With pop(0) it becomes a queue: first in, first out. That is fine for small lists; later lessons show faster tools for big ones.
Slice assignment
a[1:3] = ["x", "y", "z"] replaces a section, even with a different length; del a[::2] deletes every other item.
See it in actionShallow copy shares the inner lists
Watch the arrows. shallow's inner lists are the same boxes as original's; deep has its own.
Example 7: A stack and a queue with plain lists
The stack gives back the newest page; the queue serves the person who came first.
Output appears hereExample 8: Slice assignment
The list can grow or shrink through a slice.
Output appears hereb = a doesn't copy a list: both names point to the same list, so changing one changes the other. Make a real copy with b = a.copy() or b = a[:].What does this print?
a = [1, 2, 3] b = a b.append(4) print(len(a))
50 graded problems are waiting in Topic Practice.