Skip to content
Happy Programming Guide
Start learning
Python

The List Data Type in Python

Creating, indexing, slicing and modifying lists, the methods worth knowing, and the copying and sorting traps that catch beginners.

A backlit keyboard in a dark room

A list is Python’s ordered, changeable collection. It holds anything, in any mix, keeps the order you put things in, and grows and shrinks freely. It is the type you will reach for most, and it has two behaviours — how copying works and which methods return nothing — that account for a large share of beginner bugs.

Creating and reading#

Python
fruits = ["apple", "pear", "plum"]
mixed = [1, "two", 3.0, True, None, [4, 5]]
empty = []

print(fruits[0])      # apple  - counting starts at zero
print(fruits[-1])     # plum   - counting back from the end
print(len(fruits))    # 3

print(fruits[5])      # IndexError: list index out of range

Negative indices are worth using. items[-1] is clearer than items[len(items) - 1] and cannot be off by one.

Slicing#

Python
numbers = [0, 1, 2, 3, 4, 5]

print(numbers[1:4])     # [1, 2, 3]   - up to but NOT including index 4
print(numbers[:3])      # [0, 1, 2]
print(numbers[3:])      # [3, 4, 5]
print(numbers[-2:])     # [4, 5]
print(numbers[::2])     # [0, 2, 4]   - every second item
print(numbers[::-1])    # [5, 4, 3, 2, 1, 0] - reversed
print(numbers[:])       # a shallow copy

Slicing never raises for out-of-range values, which makes it safe in a way indexing is not:

Python
print(numbers[10:20])   # [] - no error

You can assign to a slice, which replaces that section — and the replacement need not be the same length:

Python
numbers[1:3] = ["a", "b", "c"]
print(numbers)          # [0, 'a', 'b', 'c', 3, 4, 5]

Changing a list#

Python
fruits = ["apple", "pear"]

fruits.append("plum")            # add one to the end
fruits.extend(["fig", "kiwi"])   # add several
fruits.insert(0, "cherry")       # add at a position
fruits.remove("pear")            # remove by value - ValueError if absent
last = fruits.pop()              # remove and return the last
first = fruits.pop(0)            # remove and return by index
del fruits[0]                    # remove by index
fruits.clear()                   # empty it

The methods that return None#

Python
numbers = [3, 1, 2]

result = numbers.sort()
print(result)         # None
print(numbers)        # [1, 2, 3] - the list itself changed

Methods that modify a list in place return None, not the list. Assigning their result is the single most common list bug:

Python
numbers = numbers.sort()      # numbers is now None
numbers = numbers.append(4)   # AttributeError on the next line

The rule: sort, reverse, append, extend, insert, remove and clear all return nothing. The non-mutating equivalents return a new list:

Python
ordered = sorted(numbers)          # new list, original untouched
backwards = numbers[::-1]          # new list
combined = numbers + [4, 5]        # new list

Searching#

Python
fruits = ["apple", "pear", "plum", "pear"]

print("pear" in fruits)          # True
print(fruits.index("pear"))      # 1  - the FIRST match
print(fruits.count("pear"))      # 2

if "fig" in fruits:
    print(fruits.index("fig"))   # check first - index raises otherwise

Membership testing on a list checks every element in turn. If you are doing it inside a loop over a large list, converting to a set first is often the single biggest speed-up available:

Python
blocked = set(blocked_list)      # once, before the loop
for word in message:
    if word in blocked:          # one hash lookup instead of a scan
        ...

The copying trap#

Python
a = [1, 2, 3]
b = a               # NOT a copy - both names point at one list

b.append(4)
print(a)            # [1, 2, 3, 4]

To copy:

Python
b = a.copy()        # or list(a), or a[:]

All three make a shallow copy, which copies the outer list only. Nested lists are still shared:

Python
grid = [[0, 0], [0, 0]]
copy = grid.copy()

copy[0][0] = 9
print(grid)         # [[9, 0], [0, 0]] - the inner list was shared

import copy as copy_module
deep = copy_module.deepcopy(grid)     # fully independent

The same trap in a different form, when building a grid:

Python
grid = [[0] * 3] * 3        # three references to ONE row
grid[0][0] = 9
print(grid)                 # [[9, 0, 0], [9, 0, 0], [9, 0, 0]]

grid = [[0] * 3 for _ in range(3)]    # three separate rows

Sorting#

Python
numbers = [3, 1, 2]

numbers.sort()                       # in place
numbers.sort(reverse=True)
ordered = sorted(numbers)            # a new list

words = ["banana", "Fig", "apple"]
words.sort(key=str.lower)            # case-insensitive

people = [{"name": "Ana", "age": 34}, {"name": "Sam", "age": 28}]
people.sort(key=lambda p: p["age"])
people.sort(key=lambda p: (p["age"], p["name"]))    # two keys

Python’s sort is stable, which means equal items keep their relative order. That lets you sort by several keys in separate passes, least significant first — occasionally clearer than one complicated key function.

Python
[1, "two"].sort()      # TypeError - cannot compare int and str

Removing while looping#

Python
numbers = [1, 2, 3, 4, 5, 6]

for n in numbers:
    if n % 2 == 0:
        numbers.remove(n)     # skips items

print(numbers)                # [1, 3, 5, 6] - not what you wanted

Removing shifts everything after it down by one, so the loop’s next step skips an element. Three correct approaches:

Python
numbers = [n for n in numbers if n % 2 != 0]     # clearest

for n in numbers[:]:                              # loop over a copy
    if n % 2 == 0:
        numbers.remove(n)

for i in range(len(numbers) - 1, -1, -1):        # backwards
    if numbers[i] % 2 == 0:
        del numbers[i]

Comprehensions#

Python
numbers = [1, 2, 3, 4, 5]

doubled = [n * 2 for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]

grid = [[row * col for col in range(3)] for row in range(3)]

flat = [item for row in grid for item in row]     # flatten, outer loop first

Keep them to one or two levels. A comprehension you have to read twice is a loop that should have stayed a loop.

Useful built-ins#

Python
numbers = [3, 1, 4, 1, 5]

print(sum(numbers), max(numbers), min(numbers))
print(sorted(numbers), list(reversed(numbers)))
print(len(set(numbers)))              # unique count
print(any(n > 4 for n in numbers))
print(all(n > 0 for n in numbers))

for i, value in enumerate(numbers):
    print(i, value)

for name, score in zip(names, scores):
    print(name, score)

enumerate is the answer whenever you find yourself writing for i in range(len(items)).

When not to use a list#

If you need Use
Membership tests on lots of data set
Lookup by key dict
A fixed record that will not change tuple
Cheap removal from the front collections.deque
Millions of numbers with maths on them numpy.array

Questions people ask#

What is the difference between a list and a tuple?

A list can be changed; a tuple cannot. That makes tuples usable as dictionary keys and set members, and it signals “fixed record” to whoever reads the code.

Why does my sort raise a TypeError?

The list contains types Python cannot compare, usually numbers mixed with strings. Convert them, or pass a key function that produces comparable values.

How do I remove duplicates?

list(set(items)) if order does not matter. To keep the original order, list(dict.fromkeys(items)).

Are lists slow?

Not for their purpose. Appending and index access are effectively instant. Searching by value and removing from the front are proportional to length — use a set or a deque for those.

Where to go next#

Python list comprehensions, with worked examplesRead next

Keep reading

Python

Python asyncio for Beginners

async and await let one thread handle many waiting tasks at once. What that means, when it helps, a working example that…

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *