List

Python's everyday, mutable, ordered collection — holds anything, in any mix, and can be changed after it's created.

Introduction

A list is an ordered, mutable collection written with square brackets. It can hold any mix of types, including other lists.

l = [1, 2.5, "text", [3, 4]]
print(l)
[1, 2.5, 'text', [3, 4]]

You can also build a list out of another sequence using list() — every character of a string becomes its own element.

print(list("list"))
['l', 'i', 's', 't']

Indexing & Slicing

Lists use the same positive/negative indexing and slicing rules as strings — but because lists are mutable, you can assign directly to an index or a slice to change the list in place.

l = ['b', 'i', 't', 'e']
print(l[1])
print(l[-1])

l[1] = 'y'
print(l)
i e ['b', 'y', 't', 'e']

Slicing works the same way too, including the reverse trick:

l = [0, 2, 4, 6, 8, 10]
print(l[1:4])
print(l[::-1])
[2, 4, 6] [10, 8, 6, 4, 2, 0]

Operators

+ joins two lists together (lists can only be added to other lists), and * repeats a list's contents.

l1 = [1, 2]
l2 = [3, 4]
print(l1 + l2)
print(l1 * 3)
[1, 2, 3, 4] [1, 2, 1, 2, 1, 2]

in / not in check membership, and lists can be compared element by element, the same way strings are — as soon as one pair of elements differs, that comparison decides the result.

print(2 in [1, 2, 3])
print([1, 2, 5] > [1, 2, 3])
True True

Methods

Adding elementsappend() adds one element to the end, extend() adds every element of another iterable, and insert() adds at a specific index.

l = [1, 2]
l.append(3)
l.extend([4, 5])
l.insert(0, 0)
print(l)
[0, 1, 2, 3, 4, 5]

Removing elementspop() removes and returns an item (last one by default), remove() deletes the first match by value, and clear() empties the list entirely.

l = [9, 8, 7, 6]
l.pop()
print(l)

l.remove(8)
print(l)
[9, 8, 7] [9, 7]

Orderingsort() sorts the list in place (ascending by default; pass reverse=True for descending), and reverse() flips the order.

l = [4, 1, 3, 2]
l.sort()
print(l)

l.reverse()
print(l)
[1, 2, 3, 4] [4, 3, 2, 1]

Copyingl2 = l1 doesn't make a real copy; both names point to the same list, so changing one changes the other. Use copy() to actually duplicate it.

l1 = [1, 2, 3]
l2 = l1
l3 = l1.copy()

l1.append(4)
print(l2)
print(l3)
[1, 2, 3, 4] [1, 2, 3]

Finding thingsindex() returns the position of the first match, and count() tallies how many times a value appears.

l = [5, 5, 7, 5, 9]
print(l.index(7))
print(l.count(5))
2 3