ZetCode

Python list

last modified November 16, 2026 Python 3.15

In this article we show how to work with the Python list collection.

A list is an ordered, mutable collection of values. The values of a list are called its items or elements. A list can contain values of different types and the same value multiple times; each occurrence is a distinct item. Because lists are mutable, we can add, remove, and modify items after the list is created. Internally, a CPython list is a dynamic array of references, so indexing is fast and appending at the end is cheap, while inserting or removing at the beginning has to move all the other items.

A simple list

List items can be accessed by their index. The first item has index 0, the last one has index -1.

simple.py
nums = [1, 2, 3, 4, 5]

print(nums[0])
print(nums[-1])
print(nums)
print(len(nums), type(nums))

This is a simple list of five elements. The list is delimited by square brackets [] and the elements are separated by commas.

nums = [1, 2, 3, 4, 5]

The right side of the assignment is a list display. It creates a new list containing five elements.

$ python simple.py
1
5
[1, 2, 3, 4, 5]
5 <class 'list'>

Values of different types

A list can contain values of any type, including other lists.

various_types.py
class Being:
    pass


objects = [1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3), Being(), {}]

for obj in objects:
    print(type(obj).__name__, end=' ')
print()

print(objects[:8])

We create a list containing numbers, None, a boolean value, another list, a string, a tuple, a custom object, and a dictionary. We print the type names of the items and the first eight items.

$ python various_types.py
int int float NoneType bool list str tuple Being dict 
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3)]

List initialization

Sometimes we need to initialize a list in advance to have a particular number of elements.

initialization.py
n1 = [0 for _ in range(10)]
n2 = [0] * 10
n3 = list(range(10))

print(n1)
print(n2)
print(n3)

n1[0:5] = [7] * 5
print(n1)

We create lists of ten zeros with a list comprehension and with the * operator, and a list of numbers from a range.

n1[0:5] = [7] * 5

The first five values are replaced with sevens through slice assignment.

$ python initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[7, 7, 7, 7, 7, 0, 0, 0, 0, 0]

The shared rows pitfall

The * operator repeats references, not copies. Multiplying a list of lists creates rows that are all the same object.

grid_pitfall.py
bad = [[0] * 3] * 3
bad[0][0] = 1
print(bad)
print(bad[0] is bad[1])

good = [[0] * 3 for _ in range(3)]
good[0][0] = 1
print(good)
print(good[0] is good[1])

Changing one element of bad changes the whole column, because all three rows are one list. A list comprehension evaluates [0] * 3 once for each row, so the rows are independent.

$ python grid_pitfall.py
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
True
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
False

The list function

The list function creates a list from an iterable. Without an argument, it creates an empty list.

list_fun.py
a = []
b = list()

print(a == b)
print(list((1, 2, 3)))
print(list('ZetCode'))
print(list(range(1, 6)))
print(list({'a': 1, 'b': 2}))
print(list(map(len, ['sky', 'falcon'])))

We create an empty list in two ways and lists from a tuple, a string, a range, a dictionary, and a map iterator. Iterating over a dictionary gives its keys.

$ python list_fun.py
True
[1, 2, 3]
['Z', 'e', 't', 'C', 'o', 'd', 'e']
[1, 2, 3, 4, 5]
['a', 'b']
[3, 6]

List operations

Lists support comparison, concatenation with +, repetition with *, and membership tests with in and not in.

list_oper.py
n1 = [1, 2, 3, 4, 5]
n2 = [3, 4, 5, 6, 7]

print(n1 == n2)
print(n1 + n2)
print(n1 * 3)
print(2 in n1)
print(2 in n2)
print(2 not in n2)

The == operator compares the lists item by item. The + operator creates a new list with the items of both lists, and n1 * 3 repeats the items three times. The in operator searches the list from the start, which takes time proportional to the length of the list.

$ python list_oper.py
False
[1, 2, 3, 4, 5, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
True
False
True

Comparing lists

Lists are compared lexicographically: the first pair of different items decides the result. If one list is a prefix of the other, the shorter list is smaller.

compare.py
print([1, 2, 3] < [1, 2, 4])
print([1, 2] < [1, 2, 0])
print([2] > [1, 9, 9])
print(['apple', 'pear'] < ['apple', 'plum'])
print([1, 2, 3] == [3, 2, 1])
print(sorted([[2, 1], [1, 5], [1, 2]]))

try:
    [1, 'a'] < [1, 2]
except TypeError as e:
    print(e)

Lexicographic comparison makes it possible to sort lists of lists. Items of types that cannot be compared raise a TypeError.

$ python compare.py
True
True
True
True
False
[[1, 2], [1, 5], [2, 1]]
'<' not supported between instances of 'str' and 'int'

Sequence functions

Built-in functions such as len, max, min, sum, all, and any work with lists and other iterables.

sequence_funs.py
n = [1, 2, 3, 4, 5, 6, 7, 8]

print(f'There are {len(n)} items')
print(f'Maximum is {max(n)}')
print(f'Minimum is {min(n)}')
print(f'The sum of values is {sum(n)}')
print(f'All positive: {all(x > 0 for x in n)}')
print(f'Any above 7: {any(x > 7 for x in n)}')
print(max([], default=None))

The len function returns the number of items. The all and any functions check a condition for all or for at least one item. The max function raises ValueError for an empty list unless a default value is given.

$ python sequence_funs.py
There are 8 items
Maximum is 8
Minimum is 1
The sum of values is 36
All positive: True
Any above 7: True
None

Adding list elements

The append, insert, and extend methods add new elements to a list.

adding.py
langs = []

langs.append('Python')
langs.append('Perl')
print(langs)

langs.insert(0, 'PHP')
langs.insert(2, 'Lua')
print(langs)

langs.extend(('JavaScript', 'Go'))
print(langs)

langs += ['Rust']
print(langs)

langs.append(['C', 'C++'])
print(langs)
print(len(langs))

The append method adds an item at the end of the list. The insert method places an item at the given index; the 'PHP' string is inserted at the first position and 'Lua' at the third one.

langs.extend(('JavaScript', 'Go'))

The extend method appends all items of an iterable, here a tuple. The += operator does the same.

langs.append(['C', 'C++'])

The append method adds its argument as a single item, so the list now contains a nested list and has eight elements.

$ python adding.py
['Python', 'Perl']
['PHP', 'Python', 'Lua', 'Perl']
['PHP', 'Python', 'Lua', 'Perl', 'JavaScript', 'Go']
['PHP', 'Python', 'Lua', 'Perl', 'JavaScript', 'Go', 'Rust']
['PHP', 'Python', 'Lua', 'Perl', 'JavaScript', 'Go', 'Rust', ['C', 'C++']]
8

The += operator and +

The += operator extends a list in place, while a = a + b creates a new list. The difference is visible when another variable refers to the same list.

inplace_add.py
a = [1, 2]
alias = a

a += [3]
print(a, alias, a is alias)

a = a + [4]
print(a, alias, a is alias)

b = [1, 2]
b += 'xy'
print(b)

try:
    b = b + 'xy'
except TypeError as e:
    print(e)

After a += [3], the alias variable sees the change, because the list was modified in place. After a = a + [4], a refers to a new list and alias keeps the old one. Like extend, += accepts any iterable, while + requires another list.

$ python inplace_add.py
[1, 2, 3] [1, 2, 3] True
[1, 2, 3, 4] [1, 2, 3] False
[1, 2, 'x', 'y']
can only concatenate list (not "str") to list

IndexError

An IndexError is raised when a list index is out of range.

index_error.py
n = [1, 2, 3, 4, 5]

try:
    n[0] = 10
    n[6] = 60
except IndexError as e:
    print(e)

try:
    print(n[5])
except IndexError as e:
    print(e)

print(n[:10])
print(n)

The list has five elements with indexes 0 to 4. Assigning to index 6 and reading index 5 raise an IndexError; the first assignment to index 0 succeeded before the error. Slices are more forgiving: an out-of-range slice bound is clipped to the length of the list.

$ python index_error.py
list assignment index out of range
list index out of range
[10, 2, 3, 4, 5]
[10, 2, 3, 4, 5]

TypeError

If the index of a list is not an integer or a slice, a TypeError is raised.

type_error.py
n = [1, 2, 3, 4, 5]

try:
    print(n[1])
    print(n['2'])
except TypeError as e:
    print(f'Error: {e}')

print(n[int('2')])

The string '2' is not a valid index. A string read from input has to be converted with int first.

$ python type_error.py
2
Error: list indices must be integers or slices, not str
3

Removing list elements

The pop, remove, and clear methods remove items from a list.

removing.py
langs = ['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript']
print(langs)

lang = langs.pop(3)
print(f'{lang} was removed')

lang = langs.pop()
print(f'{lang} was removed')
print(langs)

langs.remove('Ruby')
print(langs)

try:
    langs.remove('Ruby')
except ValueError as e:
    print(e)

langs.clear()
print(langs)

The pop method removes and returns the item at the given index, or the last item if no index is given. The remove method removes the first occurrence of a value and raises a ValueError if the value is not present. The clear method removes all items.

$ python removing.py
['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript']
Lua was removed
JavaScript was removed
['Python', 'Ruby', 'Perl']
['Python', 'Perl']
list.remove(x): x not in list
[]

The del statement

The del statement deletes an item or a slice of items.

removing2.py
langs = ['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript', 'Go']
print(langs)

del langs[1]
print(langs)

del langs[::2]
print(langs)

try:
    del langs[15]
except IndexError as e:
    print(e)

del langs[:]
print(langs)

We delete the second item, then every other item with an extended slice. Deleting an index that does not exist raises an IndexError. The del langs[:] statement removes all items, like clear.

$ python removing2.py
['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript', 'Go']
['Python', 'Perl', 'Lua', 'JavaScript', 'Go']
['Perl', 'JavaScript']
list assignment index out of range
[]

Removing items while iterating

Removing items from a list while looping over it skips elements, because the loop keeps an index that does not account for the shifted items.

remove_loop.py
nums = [1, 2, 2, 3, 4, 4, 5]

for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)

nums = [1, 2, 2, 3, 4, 4, 5]
nums = [n for n in nums if n % 2]
print(nums)

nums = [1, 2, 2, 3, 4, 4, 5]
for n in nums[:]:
    if n % 2 == 0:
        nums.remove(n)
print(nums)

The first loop was supposed to remove all even numbers, but the second 2 and the second 4 remain: after an item is removed, the next item moves to its position and the loop moves past it. Building a new list with a comprehension, or iterating over a copy, gives the correct result.

$ python remove_loop.py
[1, 2, 3, 4, 5]
[1, 3, 5]
[1, 3, 5]

Modifying list elements

List items are modified by assigning to an index.

modifying.py
langs = ['Python', 'Ruby', 'Perl']

langs.pop(2)
langs.insert(2, 'PHP')
print(langs)

langs[2] = 'Perl'
print(langs)

langs[-1] = langs[-1].upper()
print(langs)

nums = [1, 2, 3, 4]
for i, n in enumerate(nums):
    nums[i] = n * 10
print(nums)

One way to replace an element is to remove it and insert a new one at the same position. Assigning to the index is more straightforward. To modify all items in place, we loop with enumerate and assign through the index; assigning to the loop variable alone would not change the list.

$ python modifying.py
['Python', 'Ruby', 'PHP']
['Python', 'Ruby', 'Perl']
['Python', 'Ruby', 'PERL']
[10, 20, 30, 40]

Aliasing

Assignment does not copy a list. It creates another name for the same object, and the same holds for passing a list to a function.

aliasing.py
a = [1, 2, 3]
b = a

b.append(4)

print(a)
print(a is b)


def add_item(items):
    items.append('new')


data = ['old']
add_item(data)
print(data)

The a and b names refer to one list, so appending through b changes a. The add_item function modifies the list passed by the caller.

$ python aliasing.py
[1, 2, 3, 4]
True
['old', 'new']

Copying a list

There are several ways to make a copy of a list.

copying.py
import copy

w = ['Python', 'Ruby', 'Perl']

c1 = w[:]
c2 = list(w)
c3 = w.copy()
c4 = copy.copy(w)
c5 = [e for e in w]
c6 = [*w]

for c in (c1, c2, c3, c4, c5, c6):
    print(c, c == w, c is w)

We copy the list with a full slice, the list function, the copy method, the copy.copy function, a list comprehension, and unpacking with *. Every copy is equal to the original but is a different object.

$ python copying.py
['Python', 'Ruby', 'Perl'] True False
['Python', 'Ruby', 'Perl'] True False
['Python', 'Ruby', 'Perl'] True False
['Python', 'Ruby', 'Perl'] True False
['Python', 'Ruby', 'Perl'] True False
['Python', 'Ruby', 'Perl'] True False

Shallow and deep copies

All the copies in the previous example are shallow: the new list refers to the same items as the original. For lists of mutable objects, we need a deep copy.

deep_copy.py
import copy

matrix = [[1, 2], [3, 4]]

shallow = matrix.copy()
deep = copy.deepcopy(matrix)

matrix[0][0] = 99
matrix.append([5, 6])

print(matrix)
print(shallow)
print(deep)
print(shallow[0] is matrix[0], deep[0] is matrix[0])

Appending a row to matrix does not affect either copy, but changing an element of the first row is visible through the shallow copy, because both lists share the row. The copy.deepcopy function copies the nested lists recursively.

$ python deep_copy.py
[[99, 2], [3, 4], [5, 6]]
[[99, 2], [3, 4]]
[[1, 2], [3, 4]]
True False

Indexing list elements

Elements are accessed by their index in square brackets. Indexes start from zero; negative indexes count from the end of the list, so -1 is the last item and -2 the last but one.

indexing.py
n = [1, 2, 3, 4, 5, 6, 7, 8]

print(n[0])
print(n[-1])
print(n[-2])
print(n[3])
print(n[5])
print(n[len(n) - 1] == n[-1])

We print the first, the last, the last but one, the fourth, and the sixth items. The index -1 is a shorthand for len(n) - 1.

$ python indexing.py
1
8
7
4
6
True

The index method

The index(x, start, end) method returns the lowest index of the given value. The optional start and end arguments limit the search to a slice.

index_method.py
n = [1, 2, 3, 4, 1, 2, 3, 1, 2]

print(n.index(1))
print(n.index(2))
print(n.index(1, 1))
print(n.index(2, 2))
print(n.index(1, 2, 5))
print(n.index(3, 4, 8))

try:
    n.index(7)
except ValueError as e:
    print(e)

print([i for i, x in enumerate(n) if x == 1])

The n.index(1, 2, 5) call searches for 1 among the items with indexes 2 to 4. If the value is not found, a ValueError is raised. To find all positions of a value, we use enumerate in a list comprehension.

$ python index_method.py
0
1
4
5
4
6
list.index(x): x not in list
[0, 4, 7]

Slicing a list

Slicing extracts a part of a list into a new list. The syntax is [start:end:step]; all three parts are optional and can be negative. The item at the end index is not included in the slice.

slice.py
n = [1, 2, 3, 4, 5, 6, 7, 8]

print(n[1:5])
print(n[:5])
print(n[1:])
print(n[:])
print(n[:5] + n[5:] == n)

The n[1:5] slice contains the items with indexes 1 to 4. An omitted start defaults to the beginning of the list and an omitted end to the end of the list, so n[:] is a copy of the whole list. Because the end index is excluded, n[:5] and n[5:] together give the original list.

$ python slice.py
[2, 3, 4, 5]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
True

Slicing with a step

The third part of the slice syntax is the step. It allows us to take every n-th item.

slice_step.py
n = [1, 2, 3, 4, 5, 6, 7, 8]

print(n[1:9:2])
print(n[::2])
print(n[::1])
print(n[1::3])

The n[1:9:2] slice takes every second item, starting from the second one. The n[::2] slice takes every second item from the start, and n[1::3] every third item from the second one.

$ python slice_step.py
[2, 4, 6, 8]
[1, 3, 5, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 5, 8]

Negative indexes in slices

Negative indexes in slices count from the end of the list. With a positive step, the start must lie before the end, otherwise the slice is empty.

slice_negative.py
n = [1, 2, 3, 4, 5, 6, 7, 8]

print(n[-4:-1])
print(n[-1:-4])
print(n[-5:])
print(n[-6:-2:2])
print(n[::-1])
print(n[-1:-4:-1])

The n[-4:-1] slice returns [5, 6, 7], while n[-1:-4] is empty. A negative step goes backwards, so n[::-1] is a reversed copy and n[-1:-4:-1] takes the last three items in reverse order.

$ python slice_negative.py
[5, 6, 7]
[]
[4, 5, 6, 7, 8]
[3, 5]
[8, 7, 6, 5, 4, 3, 2, 1]
[8, 7, 6]

Slice assignment

A slice can be the target of an assignment, which replaces, removes, or inserts items. The right side must be an iterable.

slice_assign.py
n = [1, 2, 3, 4, 5, 6, 7, 8]

n[0] = 10
n[1:3] = 20, 30
n[3:] = 40, 50, 60, 70, 80
print(n)

n[1:3] = []
print(n)

n[1:1] = ['a', 'b', 'c']
print(n)

n[::2] = [0] * len(n[::2])
print(n)

try:
    n[::2] = [1, 2]
except ValueError as e:
    print(e)

A regular slice can be replaced with an iterable of any length: assigning an empty list removes the items, and assigning to the empty slice n[1:1] inserts new items. An extended slice with a step requires an iterable of exactly the same length.

$ python slice_assign.py
[10, 20, 30, 40, 50, 60, 70, 80]
[10, 40, 50, 60, 70, 80]
[10, 'a', 'b', 'c', 40, 50, 60, 70, 80]
[0, 'a', 0, 'c', 0, 50, 0, 70, 0]
attempt to assign sequence of size 2 to extended slice of size 5

Looping over a list

The for loop is the usual way to go through a list.

traverse.py
n = [1, 2, 3, 4, 5]

for e in n:
    print(e, end=' ')
print()

i = 0
while i < len(n):
    print(n[i], end=' ')
    i += 1
print()

for i, e in enumerate(n, start=1):
    print(f'{i}. {e}', end='  ')
print()

for e in reversed(n):
    print(e, end=' ')
print()

The first loop goes through the items directly. The while loop uses an index and is more verbose. The enumerate function gives both the position and the item; the start parameter sets the first number. The reversed function iterates backwards without copying the list.

$ python traverse.py
1 2 3 4 5 
1 2 3 4 5 
1. 1  2. 2  3. 3  4. 4  5. 5  
5 4 3 2 1 

Looping over several lists

The zip function iterates over several lists in parallel.

zip_lists.py
names = ['Paul', 'Lucy', 'Robert']
ages = [34, 28, 52]
cities = ['Bratislava', 'Prague', 'Vienna']

for name, age, city in zip(names, ages, cities):
    print(f'{name} is {age} and lives in {city}')

pairs = list(zip(names, ages))
print(pairs)

names2, ages2 = zip(*pairs)
print(names2, ages2)

Each iteration gives one item from each list. The zip(*pairs) call does the opposite: it splits a list of pairs into two tuples.

$ python zip_lists.py
Paul is 34 and lives in Bratislava
Lucy is 28 and lives in Prague
Robert is 52 and lives in Vienna
[('Paul', 34), ('Lucy', 28), ('Robert', 52)]
('Paul', 'Lucy', 'Robert') (34, 28, 52)

Counting list elements

The count method returns the number of occurrences of a value.

counting.py
from collections import Counter

n = [1, 1, 2, 3, 4, 4, 4, 5]

print(n.count(4))
print(n.count(1))
print(n.count(2))
print(n.count(6))

c = Counter(n)
print(c.most_common(2))

Number 4 is present three times, 1 twice, 2 once, and 6 is not present in the list. Each count call scans the whole list; to count all values at once, we use collections.Counter.

$ python counting.py
3
2
1
0
[(4, 3), (1, 2)]

Nested lists

Lists can contain other lists. To access an element of a nested list, we use additional square brackets.

nested.py
nums = [[1, 2], [3, 4], [5, 6]]

print(nums[0])
print(nums[1])
print(nums[2])

print(nums[0][0])
print(nums[0][1])
print(nums[1][0])
print(nums[2][1])

print(len(nums))
print(sum(len(row) for row in nums))

The nums[0] expression refers to the first nested list and nums[0][0] to its first element. The len function counts each nested list as one element; to count all numbers, we sum the lengths of the rows.

$ python nested.py
[1, 2]
[3, 4]
[5, 6]
1
2
3
6
3
6

Deeper nesting

Lists can be nested to any depth.

nested2.py
nums = [[1, 2, [3, 4, [5, 6]]]]

print(nums[0])
print(nums[0][2])
print(nums[0][2][2])

print(nums[0][0])
print(nums[0][2][1])
print(nums[0][2][2][0])

The [5, 6] list is nested in [3, 4, [5, 6]], which is nested in [1, 2, ...], which is the only element of the nums list. Each level of nesting needs another pair of square brackets.

$ python nested2.py
[1, 2, [3, 4, [5, 6]]]
[3, 4, [5, 6]]
[5, 6]
1
4
5

Flattening and transposing

A list comprehension with two for clauses flattens a list of lists, and zip transposes it.

flatten.py
import itertools

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print([x for row in matrix for x in row])
print(list(itertools.chain.from_iterable(matrix)))
print([list(col) for col in zip(*matrix)])
print([row[1] for row in matrix])

The itertools.chain.from_iterable function flattens the list lazily. The zip(*matrix) call passes the rows as separate arguments, so it pairs the first items of all rows, then the second items, and so on. The last line extracts the second column.

$ python flatten.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[2, 5, 8]

Unpacking a list

The items of a list can be assigned to several variables at once. A starred variable collects the remaining items into a list.

unpacking.py
point = [3, 4]
x, y = point
print(x, y)

first, *rest = [1, 2, 3, 4, 5]
print(first, rest)

*init, last = [1, 2, 3, 4, 5]
print(init, last)

head, *middle, tail = 'abcde'
print(head, middle, tail)

merged = [*point, *'xy', 0]
print(merged)

try:
    a, b = [1, 2, 3]
except ValueError as e:
    print(e)

The starred target can be at the start, in the middle, or at the end. The * operator also unpacks iterables inside a list display. If the number of variables does not match the number of items, a ValueError is raised.

$ python unpacking.py
3 4
1 [2, 3, 4, 5]
[1, 2, 3, 4] 5
a ['b', 'c', 'd'] e
[3, 4, 'x', 'y', 0]
too many values to unpack (expected 2, got 3)

Sorting a list in place

The sort method sorts the items of a list in place.

sorting.py
n = [3, 4, 7, 1, 2, 8, 9, 5, 6]
print(n)

n.sort()
print(n)

n.sort(reverse=True)
print(n)

print(n.sort())

The sort method sorts in ascending order; with reverse=True, it sorts in descending order. The method modifies the list and returns None, so n = n.sort() is a common mistake that loses the list.

$ python sorting.py
[3, 4, 7, 1, 2, 8, 9, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
None

The sorted function

The sorted function returns a new sorted list and leaves the original unchanged. It accepts any iterable.

sorting2.py
n = [3, 4, 1, 7, 2, 5, 8, 6]

print(n)
print(sorted(n))
print(n)
print(sorted('falcon'))
print(sorted((3, 1, 2), reverse=True))

The original list is not modified. Sorting a string or a tuple returns a list.

$ python sorting2.py
[3, 4, 1, 7, 2, 5, 8, 6]
[1, 2, 3, 4, 5, 6, 7, 8]
[3, 4, 1, 7, 2, 5, 8, 6]
['a', 'c', 'f', 'l', 'n', 'o']
[3, 2, 1]

Sorting with a key

The key parameter specifies a function that is called on each element; the elements are then compared by the returned values.

sort_key.py
words = ['big', 'Blue', 'seven', 'glass', 'Green', 'after', 'Antarctica']

words.sort()
print(words)

words.sort(key=str.lower)
print(words)

words.sort(key=len)
print(words)

words.sort(key=lambda w: (-len(w), w.lower()))
print(words)

By default, strings are compared by their code points, so uppercase letters come before lowercase ones. The str.lower key gives a case-insensitive order, and len sorts the words by length. A key returning a tuple sorts by several criteria: here by descending length and then alphabetically.

$ python sort_key.py
['Antarctica', 'Blue', 'Green', 'after', 'big', 'glass', 'seven']
['after', 'Antarctica', 'big', 'Blue', 'glass', 'Green', 'seven']
['big', 'Blue', 'after', 'glass', 'Green', 'seven', 'Antarctica']
['Antarctica', 'after', 'glass', 'Green', 'seven', 'Blue', 'big']

Stable sorting

Python's sort is stable: elements with equal keys keep their original relative order. This allows sorting by several criteria in successive passes.

sort_stable.py
people = [('Paul', 'IT', 34), ('Lucy', 'HR', 28), ('Anna', 'IT', 28),
          ('Mark', 'HR', 45), ('Eva', 'IT', 41)]

by_age = sorted(people, key=lambda p: p[2])
by_dept = sorted(by_age, key=lambda p: p[1])

for p in by_dept:
    print(*p)

try:
    sorted([3, 'a', 1])
except TypeError as e:
    print(e)

We sort the people by age and then by department. Within each department, the people remain ordered by age. Lists with values that cannot be compared, such as strings and integers, cannot be sorted.

$ python sort_stable.py
Lucy HR 28
Mark HR 45
Anna IT 28
Paul IT 34
Eva IT 41
'<' not supported between instances of 'str' and 'int'

Sorting by locale

Sorting by code points does not follow the alphabetical rules of natural languages. The locale.strxfrm function transforms a string so that it sorts according to the current LC_COLLATE setting.

sorting_locale.py
import locale

words = ['zem', 'štebot', 'rum', 'železo', 'prameň', 'sob', 'chlieb', 'hora']

print(sorted(words))

locale.setlocale(locale.LC_COLLATE, 'sk_SK.UTF-8')
print(sorted(words, key=locale.strxfrm))

The words are in Slovak. Without a locale, words with diacritics such as štebot and železo come last. With the Slovak collation, š follows s, ž follows z, and ch, a single letter of the Slovak alphabet, comes after h. The locale must be installed on the system.

$ python sorting_locale.py
['chlieb', 'hora', 'prameň', 'rum', 'sob', 'zem', 'štebot', 'železo']
['hora', 'chlieb', 'prameň', 'rum', 'sob', 'štebot', 'zem', 'železo']

Reversing a list

Reversing the elements should not be confused with sorting in reverse order. There are three ways to reverse a list.

reversing.py
a1 = ['bear', 'lion', 'tiger', 'eagle']
a2 = ['bear', 'lion', 'tiger', 'eagle']
a3 = ['bear', 'lion', 'tiger', 'eagle']

a1.reverse()
print(a1)

it = reversed(a2)
print(type(it).__name__)
print(list(it))

print(a3[::-1])
print(a3)

The reverse method reverses the list in place. The reversed function returns a reverse iterator, which we convert to a list. The [::-1] slice creates a reversed copy and leaves the original list unchanged.

$ python reversing.py
['eagle', 'tiger', 'lion', 'bear']
list_reverseiterator
['eagle', 'tiger', 'lion', 'bear']
['eagle', 'tiger', 'lion', 'bear']
['bear', 'lion', 'tiger', 'eagle']

List comprehensions

A list comprehension creates a new list from an iterable, with an optional condition: [expression for item in iterable if condition]. It replaces a loop that appends to an empty list.

list_comprehension.py
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

b = [e for e in a if e % 2]
print(b)

lang = 'Python'

codes = []
for c in lang:
    codes.append(ord(c))
print(codes)

print([ord(c) for c in lang])
print([e * e if e % 2 else 0 for e in a])

The first comprehension keeps the odd numbers. Then we create a list of the code points of a string with a loop and with a comprehension. The last comprehension uses a conditional expression to transform each item instead of filtering it. See Python list comprehensions for more details.

$ python list_comprehension.py
[1, 3, 5, 7, 9]
[80, 121, 116, 104, 111, 110]
[80, 121, 116, 104, 111, 110]
[1, 0, 9, 0, 25, 0, 49, 0, 81]

The map and filter functions

The map function applies a function to every item, and filter keeps the items for which a function returns a true value. Both return iterators, not lists.

map_filter.py
def positive(x):
    return x > 0


words = ['stone', 'cloud', 'dream', 'sky']
n = [-2, 0, 1, 2, -3, 4, 4, -1]

upper = map(str.upper, words)
print(type(upper).__name__)
print(list(upper))

print(list(filter(positive, n)))

print([w.upper() for w in words])
print([x for x in n if x > 0])

The map call returns a map object, which we convert to a list. A function that returns a boolean value, such as positive, is called a predicate. The last two lines produce the same results with list comprehensions, which are usually preferred.

$ python map_filter.py
map
['STONE', 'CLOUD', 'DREAM', 'SKY']
[1, 2, 4, 4]
['STONE', 'CLOUD', 'DREAM', 'SKY']
[1, 2, 4, 4]

Lists as stacks and queues

The append and pop methods make a list an efficient stack. For a queue, collections.deque is better, because removing the first item of a list moves all the other items.

stack_queue.py
from collections import deque

stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack.pop(), stack.pop(), stack)

queue = deque(['a', 'b'])
queue.append('c')
print(queue.popleft(), queue.popleft(), queue)

The stack returns the items in reverse order of insertion; the deque's popleft method returns them in the order of insertion.

$ python stack_queue.py
3 2 [1]
a b deque(['c'])

Sorted lists with bisect

The bisect module searches and inserts into sorted lists with a binary search.

bisect_demo.py
import bisect

scores = [52, 60, 68, 75, 81, 90]

bisect.insort(scores, 70)
print(scores)

print(bisect.bisect_left(scores, 75))

grades = 'FEDCBA'
for s in (45, 60, 79, 95):
    print(s, grades[bisect.bisect([50, 60, 70, 80, 90], s)])

The insort function inserts a value at the right place to keep the list sorted. The bisect_left function returns the index where a value would be inserted. The last loop maps scores to grades using a list of boundaries.

$ python bisect_demo.py
[52, 60, 68, 70, 75, 81, 90]
4
45 F
60 D
79 C
95 A

Source

Data structures – Python tutorial

Lists – Python documentation

In this article we have worked with Python lists. See also Python list slice, Python list remove, and Python list comprehensions.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.