A list is Python's most used collection: an ordered group of items that you can change. Shopping lists, exam marks, the rows of a file and the results of a search all end up in lists.
This tutorial covers creating lists, reading items by position, slicing, adding and removing items, sorting, copying (where most beginner bugs hide) and list comprehensions.
Creating a list
Put items in square brackets, separated by commas:
marks = [72, 88, 95, 64]
names = ["Ahana", "Rohan", "Meera"]
mixed = [1, "two", 3.0, True] # allowed, but usually a sign to use something else
empty = []
len(marks) gives the number of items: 4.
Indexing: reading one item
Each item has a position, called its index, starting at 0. Negative indexes count from the end:
names = ["Ahana", "Rohan", "Meera"]
names[0] # 'Ahana'
names[2] # 'Meera'
names[-1] # 'Meera': the last item
names[3] # IndexError: list index out of range
Lists are mutable, so you can replace an item in place:
names[1] = "Kabir"
print(names) # ['Ahana', 'Kabir', 'Meera']
Slicing: taking part of a list
items[start:stop] returns a new list from start up to, but not including, stop:
n = [10, 20, 30, 40, 50]
n[1:3] # [20, 30]
n[:2] # [10, 20]: from the start
n[2:] # [30, 40, 50]: to the end
n[-2:] # [40, 50]: the last two
n[::2] # [10, 30, 50]: every second item
n[::-1] # [50, 40, 30, 20, 10]: reversed
Slicing never raises an error for out-of-range positions: n[3:100] just gives [40, 50].
Adding items
| Method | What it does | Example result |
|---|---|---|
append(x) | Adds one item at the end | [1, 2, 3] → [1, 2, 3, 4] |
extend(other) | Adds every item from another list | [1, 2] + [3, 4] → [1, 2, 3, 4] |
insert(i, x) | Adds an item at position i | insert(0, 9) → [9, 1, 2] |
A common mistake is using append with a list: a.append([3, 4]) adds one item, the list itself, giving [1, 2, [3, 4]]. Use extend to add the items.
Removing items
fruits = ["mango", "apple", "guava", "apple"]
fruits.remove("apple") # removes the first "apple" only
last = fruits.pop() # removes and returns the last item: 'apple'
first = fruits.pop(0) # removes and returns the item at index 0: 'mango'
print(fruits) # ['guava']
remove raises a ValueError if the item isn't there, so check with in first if you aren't sure:
if "kiwi" in fruits:
fruits.remove("kiwi")
Searching and counting
marks = [72, 88, 95, 64, 88]
88 in marks # True
marks.index(88) # 1: position of the first 88
marks.count(88) # 2
max(marks), min(marks), sum(marks) # (95, 64, 407)
Sorting
There are two ways to sort, and the difference matters:
marks = [72, 88, 95, 64]
ordered = sorted(marks) # returns a NEW sorted list; marks is unchanged
marks.sort() # sorts marks IN PLACE and returns None
marks.sort(reverse=True) # [95, 88, 72, 64]
A classic bug is marks = marks.sort(), which sets marks to None.
Use key to sort by something other than the value itself:
names = ["Meera", "Al", "Rohan"]
sorted(names, key=len) # ['Al', 'Meera', 'Rohan']: by length
Copying: the trap that catches everyone
Assigning a list to a new name does not copy it. Both names point to the same list:
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]: a changed too!
To get an independent copy, use a.copy(), list(a) or a[:]:
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a) # [1, 2, 3]
These are shallow copies: a list of lists still shares the inner lists. For nested lists, use copy.deepcopy(a).
Looping over a list
for name in names:
print(name)
for i, name in enumerate(names, start=1):
print(i, name)
Our guide to Python for and while loops covers enumerate, zip and more.
List comprehensions
A list comprehension builds a new list from an existing one in a single line:
marks = [72, 88, 95, 64]
passed = [m for m in marks if m >= 70] # [72, 88, 95]
grace = [m + 5 for m in marks] # [77, 93, 100, 69]
labels = ["pass" if m >= 70 else "fail" for m in marks]
It is equivalent to a loop that calls append, but shorter and usually faster.
Lists vs other collections
Lists are great for ordered data, but checking x in some_list looks at every item, which is slow for big lists. If you mostly look things up, a dictionary or a set is much faster; see the cost table in Big-O notation. For large numeric data, a NumPy array is faster still.
Practice
- Given
nums = [4, 8, 15, 16, 23, 42], get the first three items, then the last two.
Show the answer
nums[:3] # [4, 8, 15]
nums[-2:] # [23, 42]
- Remove the duplicates from
[3, 1, 3, 2, 1]while keeping the original order.
Show the answer
items = [3, 1, 3, 2, 1]
unique = []
for x in items:
if x not in unique:
unique.append(x)
print(unique) # [3, 1, 2]
A shorter way: list(dict.fromkeys(items)), because dictionaries keep insertion order and keys are unique. list(set(items)) also removes duplicates, but doesn't keep the order.
- What does this print, and why?
a = [1, 2]
b = a
b += [3]
print(a)
Show the answer
[1, 2, 3]. b = a makes both names refer to the same list, and += on a list changes it in place.
- Use a list comprehension to get the squares of the odd numbers from 1 to 9.
Show the answer
[n * n for n in range(1, 10) if n % 2 == 1] # [1, 9, 25, 49, 81]
Interview questions
What is the difference between append and extend?
append(x) adds x as a single item, even if x is a list. extend(iterable) adds each item of the iterable separately.
What is the difference between sort() and sorted()?
list.sort() sorts the list in place and returns None; it only works on lists. sorted(iterable) works on any iterable and returns a new list, leaving the original unchanged.
What is the difference between a shallow and a deep copy?
A shallow copy creates a new outer list but shares the objects inside it, so changing an inner list shows up in both. A deep copy, copy.deepcopy, copies everything recursively, so the two are fully independent.
Why can't a list be a dictionary key?
Dictionary keys must be hashable, which requires them not to change. Lists are mutable, so they aren't hashable. Use a tuple instead.
What to learn next
- Store data you look up by name in Python dictionaries.
- Put list code into reusable Python functions.