Python Lists
A list stores many values in one variable, in order. You will use lists in almost every Python program you write, from a shopping cart to a set of test results.
- Create lists of any type
- Read items with indexing and slicing
- Add, change and remove items
- Loop through a list
- Sort a list two ways
- Avoid the shared-list copy bug
What is a list in Python?
A list is written with square brackets, with items separated by commas. One list can hold numbers, strings, booleans, None and even other lists.
fruits = ["apple", "banana", "cherry"]mixed = [1, "two", 3.0, True, None]empty = [] print(fruits)print(type(fruits))print(len(mixed), len(empty))['apple', 'banana', 'cherry'] <class 'list'> 5 0
Lists are ordered (items keep their position), mutable (you can change them after creating them) and they allow duplicates.
You can also build a list from any iterable with list(), for example from a string or a range.
print(list("abc"))print(list(range(1, 6)))['a', 'b', 'c'] [1, 2, 3, 4, 5]
Indexing and slicing
Every item has a position, called its index. Counting starts at 0 from the left and at -1 from the right.
| index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| nums | 10 | 20 | 30 | 40 | 50 |
| negative | -5 | -4 | -3 | -2 | -1 |
nums = [10, 20, 30, 40, 50] print(nums[0]) # first itemprint(nums[-1]) # last itemprint(nums[1:4]) # items at index 1, 2, 3print(nums[::-1]) # reversed copy10 50 [20, 30, 40] [50, 40, 30, 20, 10]
A slice nums[start:stop] includes start but stops before stop. That is why nums[1:4] returns three items. Leave out start or stop to go from the beginning or to the end.
Reading an index that does not exist raises an IndexError. A slice never does: it just returns fewer items.
nums = [10, 20, 30]print(nums[1:10])print(nums[5])[20, 30]
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(nums[5])
~~~~^^^
IndexError: list index out of rangeAdd, change and remove items
cart = ["pen", "book"] cart.append("bag") # add to the endcart.insert(1, "ink") # add at index 1cart[0] = "pencil" # replace an itemprint(cart) last = cart.pop() # remove and return the last itemprint(last, cart) cart.remove("ink") # remove by valueprint(cart)['pencil', 'ink', 'book', 'bag'] bag ['pencil', 'ink', 'book'] ['pencil', 'book']
Python list methods you will use most
| Method | What it does | Returns |
|---|---|---|
append(x) | Adds x to the end | None |
insert(i, x) | Adds x before index i | None |
extend(items) | Adds every item from another iterable | None |
remove(x) | Removes the first x; raises ValueError if it is missing | None |
pop(i=-1) | Removes the item at index i | the removed item |
index(x) | Finds the position of the first x | int |
count(x) | Counts how often x appears | int |
sort() / reverse() | Reorders the list in place | None |
clear() | Removes every item | None |
copy() | Makes a shallow copy | a new list |
append() adds its argument as one item, while extend() adds each item separately:
a = [1, 2]a.append([3, 4])print(a) b = [1, 2]b.extend([3, 4])print(b)[1, 2, [3, 4]] [1, 2, 3, 4]
Loop through a list
A for loop visits each item in order. enumerate() gives you the position and the item together, so you do not need a counter variable.
tasks = ["write tests", "run tests", "fix bugs"] for number, task in enumerate(tasks, start=1): print(f"{number}. {task}")1. write tests 2. run tests 3. fix bugs
Use in to check whether a value is in a list:
browsers = ["chromium", "firefox", "webkit"]print("firefox" in browsers)print("edge" in browsers)True False
Sort a list
scores = [72, 95, 58, 88] print(sorted(scores)) # new sorted listprint(scores) # original is unchanged scores.sort(reverse=True) # sorts in placeprint(scores)[58, 72, 88, 95] [72, 95, 58, 88] [95, 88, 72, 58]
scores.sort() changes the list and returns None. Writing scores = scores.sort() throws your list away. Use sorted(scores) when you need a new list.
Pass key= to sort by something other than the value itself, such as the length of each word:
words = ["banana", "fig", "apple"]print(sorted(words, key=len))['fig', 'apple', 'banana']
Copy a list without surprises
Assigning a list to a new name does not copy it. Both names point at the same list, so a change through one name shows up in the other.
a = [1, 2]b = a # b is the SAME list, not a copyb.append(3)print(a) c = a.copy() # c is a new listc.append(4)print(a, c)[1, 2, 3] [1, 2, 3] [1, 2, 3, 4]
Check your understanding
Predict the output
x = [1, 2, 3]y = x * 2print(y, len(y))[1, 2, 3, 1, 2, 3] 6
* repeats the list, so the three items appear twice and the new list has 6 items. x itself is unchanged.
Quick quiz
1. What does [10, 20, 30][-1] return?
Negative indexes count from the end, and -1 is the last item.
2. Which call removes and returns the last item?
pop() returns the removed item. remove() needs a value and returns None; del returns nothing.
3. After b = a and b.append(3), what is in a?
b = a makes a second name for the same list. Use a.copy() for an independent list.
4. What does [3, 1, 2].sort() evaluate to?
sort() sorts in place and returns None. sorted([3, 1, 2]) returns [1, 2, 3].
Exercise: remove duplicate emails
You have a list of signup emails with repeats. Build a list that keeps each email once, in the order it first appeared.
["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
['a@x.com', 'b@x.com', 'c@x.com']
Hint 1
A set removes duplicates but does not keep the order.
Hint 2
Dictionary keys are unique and keep insertion order.
emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"] unique = list(dict.fromkeys(emails))print(unique)['a@x.com', 'b@x.com', 'c@x.com']
dict.fromkeys(emails) builds a dictionary whose keys are the emails. A repeated key is ignored and keeps its first position, so list() of those keys is the unique list in its original order.
Program Practice: Python list programs
Practise what you just learned. Start with the easy programs and work up.
100 Python List Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python lists FAQ
What is the difference between a list and a tuple in Python?
A list is mutable, so you can add, change and remove items. A tuple is immutable: once created, its items cannot change. Use a tuple for fixed data such as coordinates. See List vs Tuple.
How do I check if an item is in a list?
Use the in operator: "apple" in fruits returns True or False.
What is the difference between append() and extend()?
append(x) adds x as one item, even if x is a list. extend(items) adds each item of items separately.
How do I remove duplicates from a list and keep the order?
Use list(dict.fromkeys(items)). list(set(items)) also removes duplicates but does not keep the original order.
Can a Python list hold different data types?
Yes. A list can mix integers, strings, floats, booleans, None and other lists, although lists of one type are easier to work with.
1 thought on “Python Lists”