W3docs

Python Lists: A Comprehensive Guide

Learn Python lists: create, access, slice, modify, sort, and use list comprehensions. Covers all built-in list methods with runnable examples.

This page covers everything you need to know about Python lists — how to create them, read and modify their contents, use slicing, apply built-in methods, write list comprehensions, work with nested lists, and unpack list values into variables.

What Is a Python List?

A list is Python's most versatile built-in data structure. It stores an ordered sequence of items, where each item can be any type: a number, a string, a boolean, another list, or any object. Lists are:

  • Ordered — items keep the position you give them.
  • Mutable — you can add, remove, or change items after the list is created.
  • Indexed — each item has an integer index starting at 0.
  • Heterogeneous — a single list can hold values of different types.

Create a list with square brackets, separating items with commas:

python— editable, runs on the server

An empty list is written as []. Lists can also contain mixed types:

mixed = [42, 'hello', True, 3.14, None]
print(mixed)
# [42, 'hello', True, 3.14, None]

Accessing List Items

Positive Indexing

Access an item by its zero-based position inside square brackets:

python— editable, runs on the server

Negative Indexing

Negative indices count backwards from the end. -1 is the last item, -2 the second-to-last, and so on — useful when you know the position from the end but not the total length:

python— editable, runs on the server

Slicing

A slice extracts a sub-list using the syntax list[start:stop:step]. The stop index is exclusive (not included).

fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']

print(fruits[1:4])   # ['banana', 'cherry', 'date']
print(fruits[:2])    # ['apple', 'banana']   — start defaults to 0
print(fruits[2:])    # ['cherry', 'date', 'elderberry'] — stop defaults to end
print(fruits[::2])   # ['apple', 'cherry', 'elderberry'] — every other item
print(fruits[::-1])  # ['elderberry', 'date', 'cherry', 'banana', 'apple'] — reversed copy

Slicing always returns a new list and never raises an IndexError, even if the indices are out of range.

Modifying List Items

Because lists are mutable, you can assign a new value to any index:

python— editable, runs on the server

You can also replace a range of items using slice assignment:

nums = [1, 2, 3, 4, 5]
nums[1:3] = [20, 30]
print(nums)
# [1, 20, 30, 4, 5]

Adding Items

append() — Add to the End

append() adds a single item to the end of the list in place:

python— editable, runs on the server

insert() — Add at a Specific Position

insert(index, value) places a new item before the given index without removing anything:

fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'mango')
print(fruits)
# ['apple', 'mango', 'banana', 'cherry']

extend() — Add Multiple Items

extend() appends all items from another iterable (list, tuple, or string) to the end:

a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)
# [1, 2, 3, 4, 5, 6]

The + operator does the same thing but returns a new list instead of modifying the original:

combined = [1, 2, 3] + [4, 5, 6]
print(combined)
# [1, 2, 3, 4, 5, 6]

Removing Items

remove() — Remove by Value

remove() deletes the first occurrence of a value. It raises ValueError if the value is not in the list:

python— editable, runs on the server

pop() — Remove by Index

pop() removes and returns the item at a given index (default: last item). This is useful when you need to both retrieve and remove an item:

fruits = ['apple', 'banana', 'cherry']
last = fruits.pop()
print(last)    # cherry
print(fruits)  # ['apple', 'banana']

first = fruits.pop(0)
print(first)   # apple
print(fruits)  # ['banana']

del — Delete by Index or Slice

The del statement removes an item by index or an entire slice:

python— editable, runs on the server

clear() — Remove All Items

clear() empties the list without deleting the list itself:

fruits = ['apple', 'banana', 'cherry']
fruits.clear()
print(fruits)
# []

Useful List Methods

Python lists come with a full set of built-in methods. See Python List Methods for the complete reference.

len() — List Length

python— editable, runs on the server

sort() — Sort In Place

sort() sorts the list in ascending order by default. Use reverse=True for descending order:

python— editable, runs on the server

Use the key parameter to sort by a custom criterion — for example, by word length:

words = ['banana', 'apple', 'cherry', 'date']
words.sort(key=len)
print(words)
# ['date', 'apple', 'banana', 'cherry']

sort() modifies the list in place. To get a sorted copy without changing the original, use the built-in sorted() function:

original = [3, 1, 2]
s = sorted(original)
print(original)  # [3, 1, 2]
print(s)         # [1, 2, 3]

See Sort Lists for more sorting patterns.

reverse() — Reverse In Place

python— editable, runs on the server

count() — Count Occurrences

count(value) returns how many times a value appears:

nums = [1, 2, 2, 3, 2, 4]
print(nums.count(2))
# 3

index() — Find a Value

index(value) returns the index of the first occurrence. It raises ValueError if not found:

nums = [1, 2, 3, 4]
print(nums.index(3))
# 2

copy() — Shallow Copy

copy() returns a new list with the same top-level items. Modifying the copy does not affect the original:

original = [1, 2, 3]
copy = original.copy()
copy.append(4)
print(original)  # [1, 2, 3]
print(copy)      # [1, 2, 3, 4]

Sorting vs. Reversing: Key Difference

sort() and reverse() both modify the list in place and return None. A common mistake is to write my_list = my_list.sort(), which replaces the list with None. Always call them as statements:

fruits = ['banana', 'apple', 'cherry']
fruits.sort()   # correct — modifies in place
# fruits = fruits.sort()  # wrong — sets fruits to None
print(fruits)
# ['apple', 'banana', 'cherry']

Nested Lists

A list can contain other lists as items, forming a 2-D (or deeper) structure:

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

print(matrix[0])     # [1, 2, 3]
print(matrix[1][2])  # 6  — row 1, column 2

Nested lists are commonly used to represent grids, tables, and matrices.

List Comprehensions

A list comprehension is a concise one-line expression for building a new list by transforming or filtering an existing iterable. The syntax is:

[expression for item in iterable if condition]

The if condition part is optional.

Squares of 1–10:

python— editable, runs on the server

Even numbers only:

evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)
# [2, 4, 6, 8, 10]

Transform strings:

fruits = ['apple', 'banana', 'cherry']
upper = [f.upper() for f in fruits]
print(upper)
# ['APPLE', 'BANANA', 'CHERRY']

List comprehensions are generally faster than an equivalent for loop with append(). See List Comprehension for advanced patterns.

Unpacking Lists

You can assign list items to individual variables in one step:

a, b, c = ['x', 'y', 'z']
print(a, b, c)
# x y z

The * (star) operator captures any number of remaining items:

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

Unpacking raises ValueError if the number of variables does not match the number of items (unless you use *).

When to Use a List

SituationRecommendation
Ordered collection that changes sizeList
Fixed collection that should not changeTuple
Fast membership testing (in)Set
Key-value mappingDictionary
Large numerical arraysnumpy.array (third-party)

Practice

Practice
Which of the following statements about Python lists are correct?
Which of the following statements about Python lists are correct?
Was this page helpful?