list#

list is Python’s mutable, ordered, indexable sequence. Heterogeneous by default. The default container when the operator doesn’t yet know which one they want.

Daily kit on list. Examples assume xs = [1, 2, 3].

Operation

Example

Effect

Construct from iterable

list(range(5))

[0, 1, 2, 3, 4].

append

xs.append(6)

Add one element to the end (O(1) amortised).

extend

xs.extend([7, 8])

Add every element of an iterable to the end.

insert

xs.insert(0, "head")

Insert before index (O(n)).

pop

xs.pop()

Remove and return the last element.

pop(i)

xs.pop(0)

Remove and return at index (O(n) at the front).

remove

xs.remove(2)

Remove first occurrence by value; ValueError if missing.

sort

xs.sort()

In-place sort.

reverse

xs.reverse()

In-place reverse.

sorted

sorted(xs)

New sorted list.

reversed

reversed(xs)

Reverse iterator.

Index, slice, repeat, concat. Examples assume xs = [1, 2, 3] and ys = [4, 5].

Form

Example

Effect

Index

xs[0]

First element.

Negative index

xs[-1]

Last element.

Slice

xs[1:4]

New list with the slice.

Stride

xs[::2]

Every second element.

Reverse copy

xs[::-1]

New reversed list.

Repeat

[0] * 8

[0, 0, 0, 0, 0, 0, 0, 0].

Concat

xs + ys

New list with both sequences.

Mutating-vs-rebinding bites under augmented assignment. xs += ys mutates the list in place; xs = xs + ys rebinds to a new list.

For the deeper container catalog (deque, Counter, defaultdict), see Data Structures.

Method catalog#

The full instance-method surface on list.

Method

Effect

append(x)

Add one element at the end (O(1) amortised).

extend(iterable)

Append every element from an iterable.

insert(i, x)

Insert before index i (O(n)).

pop([i])

Remove and return at index (default last, O(1); O(n) elsewhere).

remove(x)

Remove the first occurrence by value; ValueError if missing.

clear()

Drop every element.

index(x[, start[, end]])

First index of x in the slice; raises on miss.

count(x)

Number of occurrences.

sort(*, key=None, reverse=False)

In-place stable sort (Timsort).

reverse()

In-place reverse.

copy()

Shallow copy (same as xs[:]).

append adds one element at the end.

xs = [1, 2, 3]
xs.append(4)
xs
[1, 2, 3, 4]

extend appends every element of an iterable.

xs = [1, 2, 3]
xs.extend([4, 5])
xs
[1, 2, 3, 4, 5]

pop with no argument removes and returns the last element.

xs = [1, 2, 3]
xs.pop()
3

sort is in place and stable; pass key for custom orders.

xs = [3, 1, 2]
xs.sort()
xs
[1, 2, 3]

index returns the first index of a value or raises.

[1, 2, 3, 2].index(2)
1

Operator overloading#

list implements the mutable-sequence dunders.

Operator

Dunder

Returns

a + b

__add__

New list (concatenation).

a * n

__mul__

Repeated list.

a == b

__eq__

Element-wise equality.

a < b

__lt__

Lexicographic less than.

a in b

__contains__

Element membership test.

a[i] / a[i:j]

__getitem__

Indexing and slicing.

a[i] = x

__setitem__

In-place element assignment.

del a[i]

__delitem__

In-place delete.

len(a)

__len__

Length.

iter(a)

__iter__

Iteration.

reversed(a)

__reversed__

Reverse iterator.

a += b

__iadd__

In-place extend.

a *= n

__imul__

In-place repetition.

bool(a)

__bool__

False only for the empty list.

A queue class can use __getitem__ / __len__ to behave as a read-only sequence over an internal deque.

from collections import deque

class Queue:
    def __init__(self, items=()): self._q = deque(items)
    def push(self, x): self._q.append(x)
    def __getitem__(self, i): return self._q[i]
    def __len__(self):  return len(self._q)

q = Queue([1, 2, 3]); q.push(4)
q[0], q[-1], len(q)
(1, 4, 4)

__add__ and __iadd__ make a wrapper class support both copy-concat and in-place extend.

class Stack:
    def __init__(self, xs=()): self.xs = list(xs)
    def __add__(self, other):  return Stack(self.xs + other.xs)
    def __iadd__(self, other): self.xs.extend(other.xs); return self
    def __repr__(self):        return f"Stack({self.xs})"

a = Stack([1, 2]); b = Stack([3, 4]); a += b; a
Stack([1, 2, 3, 4])

References#