The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Create a listitems = ["alpha", "beta"]View examples
Create from an iterableitems = list(range(1, 5))View examples
Read the first itemfirst = items[0]View examples
Read the last itemlast = items[-1]View examples
Replace an itemitems[1] = "updated"View examples
Append one itemitems.append("beta")View examples
Append many itemsitems.extend(["gamma", "delta"])View examples
Remove by valueitems.remove("beta")View examples
Remove the last itemvalue = items.pop()View examples
Remove by indexvalue = items.pop(0)View examples
Slice a rangesubset = items[1:4]View examples
Slice with a stepsubset = items[::2]View examples
Reverse with slicingreversed_items = items[::-1]View examples
Transform every itemsquares = [x ** 2 for x in items]View examples
Filter itemsevens = [x for x in items if x % 2 == 0]View examples
Sort the existing listitems.sort()View examples
Create a sorted copyresult = sorted(items)View examples
Sort with a keyitems.sort(key=str.lower)View examples
Sort descendingitems.sort(reverse=True)View examples

Python lists are ordered, mutable collections. They can hold mixed values, but code is usually clearer when each list contains one consistent kind of item.

Step by step

Detailed examples

01

Create lists with literals or constructors

List literals are clearest for known values. The list constructor is useful when consuming another iterable such as a range, tuple, or generator.

Literal and iterable
colors = ["blue", "green", "orange"]
numbers = list(range(1, 5))

print(colors)
print(numbers)
Output
['blue', 'green', 'orange']
[1, 2, 3, 4]
Back to quick reference ↑
02

Read and update items by index

Indexes begin at zero. Negative indexes count from the end, with -1 selecting the last item. An out-of-range index raises IndexError.

Positive and negative indexes
tasks = ["plan", "build", "test"]
print(tasks[0])
print(tasks[-1])

tasks[1] = "implement"
print(tasks)
Output
plan
test
['plan', 'implement', 'test']
Back to quick reference ↑
03

Append one item or extend with many

Append adds its argument as one item. Extend iterates over its argument and adds each value separately. Both mutate the existing list and return None.

Append versus extend
languages = ["HTML", "CSS"]
languages.append("Python")
languages.extend(["SQL", "Bash"])
print(languages)
Output
['HTML', 'CSS', 'Python', 'SQL', 'Bash']
Back to quick reference ↑
04

Remove by value or position

Remove deletes the first matching value and raises ValueError when absent. Pop removes by index and returns the removed value; without an index, it uses the last item.

Remove and pop
queue = ["Ada", "Linus", "Grace"]
queue.remove("Linus")
next_person = queue.pop(0)

print(next_person)
print(queue)
Output
Ada
['Grace']
Back to quick reference ↑
05

Select a range with slicing

The stop index is excluded. Any component may be omitted, and a negative step reverses direction. A simple full slice creates a shallow copy.

Common slices
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])
print(numbers[::2])
print(numbers[::-1])
Output
[1, 2, 3]
[0, 2, 4]
[5, 4, 3, 2, 1, 0]
Back to quick reference ↑
06

Transform and filter with comprehensions

A comprehension builds a new list. Keep it readable: when transformation or filtering needs several steps, use a normal loop or helper function instead.

Squares of even numbers
numbers = range(1, 9)
even_squares = [number ** 2 for number in numbers if number % 2 == 0]
print(even_squares)
Output
[4, 16, 36, 64]
Back to quick reference ↑
07

Sort in place or return a sorted copy

List.sort changes the list and returns None. The sorted function accepts any iterable and returns a new list. Both support key and reverse arguments.

Sort records by one field
users = [
    {"name": "Mina", "score": 82},
    {"name": "Ravi", "score": 95},
    {"name": "Jo", "score": 88},
]

ranking = sorted(users, key=lambda user: user["score"], reverse=True)
print([user["name"] for user in ranking])
Output
['Ravi', 'Jo', 'Mina']
Back to quick reference ↑

Local code tester

Run Python lists in your browser

Pyodide loads from this site only after you press Run. Edit the code, inspect its output, or stop and reset the isolated worker.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software FoundationData Structures — More on Listsdocs.python.org
  2. Python Software FoundationCommon Sequence Operationsdocs.python.org
  3. Python Software FoundationMutable Sequence Typesdocs.python.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback