Python Lists
Working with lists: indexing, slicing, methods, sorting, and list comprehensions for ordered collections.
What you'll learn
- Create, index, and slice lists
- Add and remove elements with append, insert, pop, remove
- Sort and reverse lists in place and with sorted()
- Use list comprehensions for concise transformations
- Copy lists and avoid shared-reference bugs
Concept
Creating Lists
A list is an ordered, mutable collection that can hold any type of object. Lists are Python's most versatile data structure:
empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
nested = [[1, 2], [3, 4], [5, 6]]
Lists can hold mixed types and be nested to any depth. They are the go-to structure whenever you need an ordered, changeable sequence.
Indexing and Slicing
Lists support the same indexing and slicing syntax as strings:
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # apple
print(fruits[-1]) # date
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[::-1]) # reversed list
Slicing a list always returns a new list — the original is unchanged.
Adding and Removing Elements
fruits = ["apple", "banana"]
# Adding
fruits.append("cherry") # add to end
fruits.insert(0, "apricot") # insert at index 0
fruits.extend(["date", "fig"]) # add multiple
# Removing
fruits.pop() # remove and return last
fruits.pop(0) # remove and return index 0
fruits.remove("banana") # remove first match by value
.append()adds one element to the end — the most common list operation.extend()adds all elements from another iterable.pop()removes by index (default: last) and returns the value.remove()removes by value (first match only)
Sorting
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort() # in-place: [1, 1, 2, 3, 4, 5, 6, 9]
numbers.sort(reverse=True) # descending
# sorted() returns a new list — original unchanged
original = [3, 1, 4]
ordered = sorted(original)
# Sort by a key function
words = ["banana", "apple", "cherry"]
words.sort(key=len) # sort by length
Use .sort() when you want to modify the list in place, and sorted() when you want a new sorted list without changing the original. The key parameter lets you sort by any function.
List Comprehensions
A concise way to create lists from existing iterables:
squares = [x ** 2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
pairs = [(x, y) for x in range(3) for y in range(3)]
List comprehensions are both faster and more readable than equivalent for-loops with .append(). They are a hallmark of idiomatic Python.
Copying Lists
Because variables are references, b = a does not copy a list — both point to the same object:
a = [1, 2, 3]
b = a # same object!
b.append(4)
print(a) # [1, 2, 3, 4] — a changed too
# To copy:
shallow = a.copy() # or list(a), or a[:]
import copy
deep = copy.deepcopy(a) # for nested lists
Use .copy() for a shallow copy (one level) and copy.deepcopy() for nested structures.
Example
# Creating and indexing
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # apple
print(fruits[-1]) # date
print(fruits[1:3]) # ['banana', 'cherry']
# Adding and removing
fruits.append("fig")
fruits.insert(0, "apricot")
print(fruits) # ['apricot', 'apple', 'banana', 'cherry', 'date', 'fig']
removed = fruits.pop() # removes 'fig'
fruits.remove("banana") # removes by value
print(fruits)
# Sorting
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
words = ["banana", "apple", "cherry"]
words.sort(key=len)
print(words) # ['apple', 'banana', 'cherry'] (by length)
# List comprehension
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
evens = [x for x in range(20) if x % 2 == 0]
print(evens)
# Copying — avoid shared reference
original = [1, 2, 3]
copy = original.copy()
copy.append(4)
print(original) # [1, 2, 3] — unchanged
Shows list creation, indexing/slicing, append/insert/pop/remove, in-place sort with a key function, list comprehensions for filtering and mapping, and the copy() method to avoid shared-reference bugs.
Try it
- JSON Formatter
Lists serialize directly to JSON arrays — format and inspect them.
- Text Counter
Splitting text into lists of words is a common list operation.
Common mistakes
The mistake
Using b = a and expecting an independent copy of the list
The fix
b = a creates a reference to the same list object. Use b = a.copy(), b = list(a), or b = a[:] for a shallow copy. For nested lists, use copy.deepcopy(a).
The mistake
Removing elements while iterating over the same list
The fix
Modifying a list while iterating over it skips elements and causes bugs. Iterate over a copy (for x in lst[:]:) or build a new list with a comprehension instead.
Related Resources
Related Cheatsheets
- Python Cheatsheet
All list methods, slicing, and comprehension syntax.
Practice Python Lists
14 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.