New in 2026: Master Python for AI, Data Science

PythonPython Basic TutorialPython Data Structures

Python Lists: The Complete 2026 Guide

Python list tutorial — list methods, indexing, slicing, comprehension, and practical examples. Complete guide for beginners.

This is the reference page for Python lists: storage, every method and its return value, operation costs, and the semantics tutorials skip — length-changing slice assignment, stable sorts, shallow versus deep copies, and == versus is. If you have never used a list, start with the beginner-friendly walkthrough and come back when you need the details.

The examples run on CPython 3.13; the semantics described here hold on Python 3.8 and later except where a version is noted.

The page is organized so you can read it in order or jump to a section:

  • Storage and index layout
  • Every method, with return value, mutation, and complexity
  • Edge cases: bounds, slicing, assignment, sorting, comparison, copying
  • Performance, from amortized appends to quadratic membership tests
  • Idioms for unpacking, enumeration, zipping, and key-based sorting
  • When a list is the wrong sequence

What Is a List?

A list is an ordered, mutable collection of items. Unlike arrays in other languages, a Python list can hold objects of different types — strings, integers, floats, even other lists — all in the same container. If you are new to Python, start with the Introduction to Python Programming to understand the fundamentals before diving into data structures.

Prerequisites

You should have Python 3.8 or later and be comfortable writing loops and functions. This page assumes you have used a list before and covers what is easy to get wrong rather than the syntax; the beginner guide linked at the top covers that. Familiarity with Python strings helps, because both share indexing and slicing syntax.

List Structure — Index Layout

Index:      0         1          2          3          4
          ┌──────────┬──────────┬──────────┬──────────┬──────────┐
Value:    │  'apple' │ 'banana' │  'cherry'│  'mango' │  'kiwi'  │
          └──────────┴──────────┴──────────┴──────────┴──────────┘
             -5        -4         -3         -2         -1
                                       Negative indexing

Creating Lists

Python offers two primary ways to create lists. The list() constructor is useful when you want to convert another iterable (like a string or tuple) into a list. The literal [] syntax is faster and more readable for known values.

# Two ways to create an empty list
list1 = list()
list2 = []

# With initial values
fruits = ['apple', 'banana', 'cherry', 'mango', 'kiwi']

# Mixed types
mixed = ['hello', 123, 3.14, True, None]

# Nested list (2D structure)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(f"Original: {fruits}")
print(f"Length: {len(fruits)}")

Output

Original: ['apple', 'banana', 'cherry', 'mango', 'kiwi']
Length: 5

Indexing and Slicing

Lists share string indexing syntax, but they are mutable, so you can assign to an index. Index 0 is the first element, and negative indices count back from the end, with -1 as the last. The Python Strings guide covers the details, since the syntax is identical.

fruits = ['apple', 'banana', 'cherry', 'mango', 'kiwi']
print(f"Index 2: {fruits[2]}")        # Third element
print(f"Last: {fruits[-1]}")           # Last element
print(f"Slice [1:4]: {fruits[1:4]}")  # Elements at index 1, 2, 3

# Modify by index
fruits[0] = 'avocado'
print(f"After modify: {fruits}")

Output

Index 2: cherry
Last: kiwi
Slice [1:4]: ['banana', 'cherry', 'mango']
After modify: ['avocado', 'banana', 'cherry', 'mango', 'kiwi']

List Methods

Python lists have a fixed set of methods for adding, removing, and reorganizing elements. Most mutate in place and return None; pop() also returns the removed element, while copy(), count() and index() return values without changing the list. Signatures follow the official documentation.

Complete Method Reference

MethodWhat it doesReturnsMutates?Time complexity
append(x)Adds x at the endNoneYesO(1) amortized
extend(iterable)Adds each item of an iterableNoneYesO(k)
insert(i, x)Inserts x before index iNoneYesO(n)
remove(x)Deletes the first xNoneYesO(n)
pop([i])Removes and returns item i (default: last)The itemYesO(1) at the end, O(n) elsewhere
clear()Removes all itemsNoneYesO(n)
index(x)First position of xintNoO(n)
count(x)Number of items equal to xintNoO(n)
sort()Sorts in place with <NoneYesO(n log n)
reverse()Reverses in placeNoneYesO(n)
copy()Shallow copyA new listNoO(n)

Two rules cover most of the confusion: a method that mutates returns None, so items = items.sort() gives None; and only pop() returns what it removed. Complexities assume CPython’s dynamic array, with n = len(list).

append() — Add to End

The append() method adds a single element to the end of the list. It is O(1) amortized time complexity, making it efficient even for large lists.

fruits = ['apple', 'banana', 'cherry']
fruits.append('mango')
print(f"After append: {fruits}")

Output

After append: ['apple', 'banana', 'cherry', 'mango']

insert() — Add at Position

Use insert() to add an element at a specific index. Elements at and after the insertion point are shifted to the right. Note that inserting at the end (insert(len(list), x)) is equivalent to append().

fruits = ['apple', 'banana', 'cherry', 'mango', 'kiwi']
fruits.insert(2, 'orange')
print(f"After insert at index 2: {fruits}")

Output

After insert at index 2: ['apple', 'banana', 'orange', 'cherry', 'mango', 'kiwi']

pop() — Remove and Return

The pop() method removes and returns the element at the given index. Calling pop() without an argument removes and returns the last element. It is one of the few list methods that returns a value — count() and index() do too.

fruits = ['apple', 'banana', 'cherry', 'mango', 'kiwi', 'grape']
removed = fruits.pop()
print(f"Popped: {removed}")
print(f"After pop: {fruits}")

# Pop from specific index
removed = fruits.pop(2)
print(f"Popped index 2: {removed}")
print(f"After pop(2): {fruits}")

Output

Popped: grape
After pop: ['apple', 'banana', 'cherry', 'mango', 'kiwi']
Popped index 2: cherry
After pop(2): ['apple', 'banana', 'mango', 'kiwi']

remove() — Remove by Value

The remove() method removes the first occurrence of a value. It raises ValueError if the value is not found. Unlike pop(), it does not return the removed value.

numbers = [1, 2, 3, 2, 4, 2]
numbers.remove(2)  # Removes first occurrence only
print(f"After remove(2): {numbers}")

Output

After remove(2): [1, 3, 2, 4, 2]

extend() — Merge Lists

Use extend() to append all elements from another iterable (list, tuple, string, etc.) to the end of the list. This is different from append(), which would add the entire iterable as a single element.

a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(f"After extend: {a}")

# Contrast with append
c = [1, 2, 3]
c.append([4, 5, 6])
print(f"After append (wrong): {c}")

Output

After extend: [1, 2, 3, 4, 5, 6]
After append (wrong): [1, 2, 3, [4, 5, 6]]

sort() and reverse()

The sort() method sorts the list in place (modifies the original) in ascending order by default. Use reverse=True for descending order. The reverse() method reverses the list in place. Note that sorted(list) returns a new sorted list without modifying the original — an important distinction when you need to preserve the input.

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(f"Sorted: {numbers}")

numbers.reverse()
print(f"Reversed: {numbers}")

# Sort descending
numbers.sort(reverse=True)
print(f"Sorted desc: {numbers}")

Output

Sorted: [1, 1, 2, 3, 4, 5, 6, 9]
Reversed: [9, 6, 5, 4, 3, 2, 1, 1]
Sorted desc: [9, 6, 5, 4, 3, 2, 1, 1]

Edge Cases and Semantics

These rules separate code that works on the happy path from code that is correct.

Negative Indices and Bounds

A negative index resolves as len(list) + i, so -1 is the last element and -len(list) the first; anything outside that range raises IndexError, as does any index at or past len(list).

The exception type says which lookup failed. Position-based operations — lst[i], pop(i) — raise IndexError; value-based ones — remove(x), index(x) — raise ValueError when no equal element exists. Slices are exempt: out-of-range bounds are clamped, so lst[100:] returns [].

Slicing with a Step

The full form is lst[start:stop:step]. start is inclusive, stop exclusive, and a negative step walks backward, so lst[::-1] reverses the list. Every slice returns a new list — lst[::-1] is a reversed copy, not a view, and costs O(n). With a negative step, an omitted stop includes index 0, so lst[3:0:-1] stops before it.

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(digits[::-1])
print(digits[1:8:2])
print(digits[-3:])
print(digits[6:2])
print(digits[100:])

Output

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

Slice Assignment

Assigning to a slice replaces its elements, and the replacement can differ in length: lst[1:4] = ['B', 'C'] shrinks three to two, while lst[1:2] = ['b', 'c', 'd'] grows one to three. del lst[1:3] removes a range; del lst[::2] removes every second element.

Two restrictions matter: an extended slice (step other than 1) accepts only a sequence of the same length, otherwise ValueError; and lst[:] = other keeps the same list object, which matters when another name or closure references it.

letters = ['a', 'b', 'c', 'd', 'e']
letters[1:4] = ['B', 'C']
print(letters)

letters[1:2] = ['b', 'c', 'd']
print(letters)

letters[::2] = ['A', 'C', 'E']
print(letters)

try:
    letters[::2] = ['X']
except ValueError as exc:
    print(f"ValueError: {exc}")

Output

['a', 'B', 'C', 'e']
['a', 'b', 'c', 'd', 'C', 'e']
['A', 'b', 'C', 'd', 'E', 'e']
ValueError: attempt to assign sequence of size 1 to extended slice of size 3

Sorting: Stability and key=

list.sort() is stable: equal elements keep their relative order. That makes multi-key sorting work — sort by the secondary key, then by the primary, and the second sort preserves the first inside each group. reverse=True keeps that guarantee; sorting and then reversing does not.

The key function runs once per element, not once per comparison, so a key that builds a tuple costs n calls rather than O(n log n). Sorting raises TypeError when elements are not comparable with <, which in Python 3 includes mixing numbers and strings. CPython uses Timsort: O(n log n) worst case, O(n) on already-sorted data.

Comparing Lists

== compares element by element and recurses into nested lists, so [[1], [2]] == [[1], [2]] is True. Ordering is lexicographic: compare the first pair that differs, and if one list is a prefix of the other, the shorter is smaller — [1, 2] < [1, 2, 3]. A list never equals a tuple of the same contents.

is asks whether two names point to the same object. [1] == [1] is True because the contents match; [1] is [1] is False because two literals create two lists. Use is for identity only — None, sentinels, and the rare case where you need the same container.

Aliasing, copy(), and deepcopy()

b = a copies nothing; both names point to one list, so b.append(x) changes a. a.copy(), a[:] and list(a) make a new outer list but share nested objects — the classic nested-list bug, and why [[]] * 3 is three references to one list.

copy.deepcopy() copies recursively, using a memo dictionary so shared references and cycles survive. It is much slower than a shallow copy; use it only when nested objects must be independent.

import copy

a = [[1, 2], [3, 4]]
shallow = a.copy()
deep = copy.deepcopy(a)

shallow[0].append(99)
deep[1].append(100)
print(f"a:       {a}")
print(f"shallow: {shallow}")
print(f"deep:    {deep}")
print(f"shared inner list: {a[0] is shallow[0]}")
print(f"shared inner list: {a[0] is deep[0]}")

Output

a:       [[1, 2, 99], [3, 4]]
shallow: [[1, 2, 99], [3, 4]]
deep:    [[1, 2], [3, 4, 100]]
shared inner list: True
shared inner list: False

List Comprehension

Comprehensions build a list from an existing sequence in one expression. They combine filtering and transformation and are faster than an equivalent for loop because the loop runs in C. Think of them as map() and filter() combined, with the clauses read left to right.

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

# Filter + transform
evens = [x for x in numbers if x % 2 == 0]
print(f"Evens: {evens}")

# Transform all
squares = [x**2 for x in numbers]
print(f"Squares: {squares}")

# Conditional transform
labels = ['even' if x % 2 == 0 else 'odd' for x in [1, 2, 3, 4]]
print(f"Labels: {labels}")

Output

Evens: [2, 4, 6, 8, 10]
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Labels: ['odd', 'even', 'odd', 'even']

Nested Lists — 2D Data Structures

A nested list is a list containing other lists as its elements. This lets you represent matrices, grids, and tabular data. Access elements using double indexing: matrix[row][col].

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(f"Row 2: {matrix[1]}")
print(f"matrix[2][1]: {matrix[2][1]}")  # row 3, col 2

# Iterate nested list
for row in matrix:
    print(row)

Output

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

Performance Notes

append() is amortized O(1). The list keeps spare capacity; when it runs out, CPython allocates a larger block — about one eighth more slots — and copies the pointers. The reallocation is O(n), but rare enough that the average append stays constant.

insert(0, x) and pop(0) are O(n): every element after the insertion point moves one slot, so a loop over the front of a 100,000-element list does billions of pointer moves. collections.deque gives O(1) appends and pops at both ends; use it for queues.

When the final size is known, preallocate with [None] * n and assign by index instead of growing one append at a time. Comprehensions are typically 1.3–2× faster than append loops because the loop runs in C. Membership is the other surprise: x in lst is O(n), so lookups inside a loop are O(n²); build a set for repeated tests.

Sorting is O(n log n) with up to n/2 pointers of temporary storage; reverse() is O(n). Both run in C, so the Python loop they replace is almost always slower.

from collections import deque

queue = deque([1, 2, 3])
queue.appendleft(0)
queue.append(4)
print(queue)
print(queue.popleft(), queue.pop())
print(queue)

# Preallocate when the final size is known
squares = [0] * 5
for i in range(5):
    squares[i] = i * i
print(squares)

Output

deque([0, 1, 2, 3, 4])
0 4
deque([1, 2, 3])
[0, 1, 4, 9, 16]

Idioms That Save Code

Most real list code is a handful of patterns. These are worth recognizing on sight.

  • Unpacking with a star — first, *rest = items splits head and tail; the starred name is always a list, even when it collects nothing.
  • enumerate — for i, value in enumerate(items, start=1) replaces a manual counter.
  • zip — pairs iterables positionally and stops at the shorter one; strict=True (3.10+) raises ValueError instead of truncating.
  • sorted with key — returns a new list; key=lambda r: r[1] or operator.itemgetter(1) avoids work per comparison.
  • any, all, next — any(x < 0 for x in items) and all(...) short-circuit; next((x for x in items if x > 4), None) returns the first match or a default.
items = [3, -1, 4, -1, 5]
first, *rest = items
print(first, rest)

for position, value in enumerate(items, start=1):
    print(position, value, end="; ")
print()

names = ["ada", "grace"]
roles = ["math", "navy"]
print(list(zip(names, roles)))

scores = [("ada", 90), ("grace", 85), ("alan", 95)]
print(sorted(scores, key=lambda pair: pair[1], reverse=True))
print(any(x < 0 for x in items), all(x > 0 for x in items))
print(next((x for x in items if x > 4), None))

Output

3 [-1, 4, -1, 5]
1 3; 2 -1; 3 4; 4 -1; 5 5; 
[('ada', 'math'), ('grace', 'navy')]
[('alan', 95), ('ada', 90), ('grace', 85)]
True False
5

Choosing the Right Sequence

A list is the default sequence and usually the right one. It stops being right when you need immutability, hashability, set operations, or compact numeric storage.

TypeOrderedMutableDuplicatesLookupUse it for
listYesYesYesO(1) index, O(n) valueOrdered data that changes
tupleYesNoYesO(1) index, O(n) valueFixed records; keys if hashable
setNoYesNoO(1) averageMembership, deduplication
array.arrayYesYesYesO(1) indexCompact numeric buffers
numpy.ndarrayYesYesYesO(1) indexVectorized numeric arrays

The memory difference is larger than the table suggests. A list holds pointers, and each element is a separate object, so a million integers cost about 8 MB of pointers plus the integers. array.array and NumPy store the values directly, 4 or 8 bytes each, which is why they win for numeric data.

Two conversions matter: list(dict.fromkeys(seq)) deduplicates while preserving first-seen order, which list(set(seq)) does not; and a tuple is hashable only if every element is, so one containing a list still fails as a key.

Common Mistakes and Gotchas

  • Shallow copy confusion — copy() and [:] are shallow; nested lists and dicts stay shared. Use copy.deepcopy() for a full copy.
  • Modifying a list while iterating — removing elements shifts the indices. Iterate over a copy (for item in list[:]) or filter with a comprehension.
  • append() vs extend() — append(x) adds x as one element; extend(iterable) unpacks it, so list.append([1, 2]) gives [..., [1, 2]].
  • Reference vs value assignment — b = a shares one list. Use b = a.copy() or b = list(a) for an independent copy.
  • sort() vs sorted() — sort() mutates and returns None; sorted() returns a new list. Assigning the result of sort() is the usual way to turn a list into None.
  • Mixed types — sort() and < raise TypeError when elements cannot be compared, such as strings mixed with integers. Normalize the data or pass key=str.

Common Operations Summary

OperationDescription
len(list)Number of items
list.index(x)First index of x (raises ValueError if not found)
list.count(x)Count occurrences of x
x in listMembership test — returns True/False
list.copy()Shallow copy of the list
list.clear()Remove all items
sorted(list)Return new sorted list (does not modify original)
list[a:b] = iterableSlice assignment — can grow or shrink the list
del list[i]Delete by position; returns nothing

Summary and Next Steps

Python lists are a dynamic array of pointers with a large, stable method surface — ordered, mutable, and enough for most everyday tasks without external libraries. You now know how to create, index, slice, modify, and iterate over them, and which pitfalls to avoid.

From here, explore these related topics:


Frequently Asked Questions

Is a Python list an array or a linked list?

It is a dynamic array of pointers: a contiguous block of object references with spare capacity at the end. Indexing is O(1) because element i sits at a fixed offset, and iteration is fast because the slots are adjacent. Growth reallocates the block and copies the pointers, which is why append() is amortized O(1).

Which is faster, a for loop with append or a list comprehension?

The comprehension, usually by 30–50% for a simple transform, because its loop runs in C and appends without a method lookup per item. The gap shrinks as per-item work grows. If the results are consumed once, a generator expression passed to sum() or any() avoids building the list.

Do list slices copy the data?

Yes. Every slice creates a new list containing references to the same objects, so lst[1:3] allocates and copies two pointers. That is what makes lst[:] a shallow copy. Slice assignment is the in-place counterpart and can change the length.

Why is insert(0, x) O(n) when append() is O(1)?

append() writes into spare capacity at the end; insert(0, x) shifts every existing pointer right, which is n moves, and pop(0) shifts them back. Use collections.deque for a queue — its appendleft() and popleft() are O(1).

Can I use a list as a dictionary key or a set element?

No. Lists are mutable and unhashable, so {[1]: 'a'} raises TypeError: unhashable type: 'list'. Convert to a tuple when the contents are hashable, or a frozenset when order does not matter.

How do I remove every occurrence of a value?

Build a new list with a comprehension: [x for x in lst if x != value]. It is O(n) and avoids the index-shifting bug of removing while iterating. To keep the same list object, assign back into the full slice: lst[:] = [x for x in lst if x != value].

What does stable sorting mean in practice?

Equal elements keep their original relative order. That lets you sort by several keys in sequence and keep the earlier order inside each group. sort(reverse=True) is stable in the same sense; sorting and then reversing flips every equal group.

Related posts
Python

Pydantic Agent Basics: A Complete 2026 Tutorial

ProgrammingPython

Production-Ready MCP Servers — Security, Testing & Deployment

ProgrammingPython

Build Your First MCP Server with Python SDK — Fundamentals

ProgrammingPython

Connect FastAPI to MCP — Two Integration Patterns

Leave a Reply