PythonPython ListsPython list fundamentals

What is a list in Python?

Question 76 of 88 · Updated

On this page

A list is Python's built-in mutable sequence type for storing an ordered collection of objects. A list can be empty, contain duplicate elements, hold objects of different types, and grow or shrink while a program runs. Its type is list, and a common way to express a list is with comma-separated expressions inside square brackets.

Lists are useful when a program needs to preserve a sequence of items, access items by position, or accumulate and update a collection. Unlike a set, a list does not enforce uniqueness. Unlike a tuple, a list permits its element references to be changed.

1. A first list#

PYTHON
items = ['pen', 'book', 'pen'] print(type(items).__name__, len(items)) print(items) print(items[0], items[-1])

Output:

list 3
['pen', 'book', 'pen']
pen pen

This list contains three elements in a defined order. The repeated value pen occupies two positions and counts as two elements. The first element has index zero, and the negative index -1 selects the final element.

Ordering means that positions are meaningful. It does not mean the list is automatically sorted. A list preserves its current sequence until an operation changes that sequence.

2. Essential list characteristics#

CharacteristicMeaning
OrderedElements have positions and can be traversed in sequence
MutableElements can be replaced, inserted or removed
Variable lengthThe collection can grow or shrink
Duplicates allowedEqual values can occupy multiple positions
HeterogeneousElements need not all have the same type
Indexable and sliceableIndividual positions and subsequences can be selected
IterableA for loop can visit its elements in order
UnhashableAn ordinary list cannot be used directly as a dictionary key or set element

Heterogeneous storage is permitted, but it is not always desirable. A list of numeric measurements generally has a clearer contract when its elements are consistently numeric. A list of records may similarly benefit from a defined schema.

A list does not enforce Python type annotations at runtime merely because it is annotated as list[int]. Such annotations communicate expectations to readers, static analysis tools and libraries; enforce the required data contract at the appropriate boundary.

3. List literals and iterable construction#

PYTHON
values = [10, 'ten', True, None] print([type(value).__name__ for value in values]) print(list(range(2, 7, 2))) print(list('abc'))

Output:

['int', 'str', 'bool', 'NoneType']
[2, 4, 6]
['a', 'b', 'c']

Square brackets with comma-separated expressions create a list literal. Empty brackets produce a new empty list. The list constructor can also consume an iterable and materialize its elements in iteration order.

The range example generates the integers 2, 4 and 6. The string example produces three one-code-point strings because iterating a str yields individual code points.

Construction differs from parsing. Calling list on a comma-separated string does not parse a record into fields; the string is iterated character by character. Use a suitable splitting or parsing operation when that is the actual requirement.

A list constructor receiving an existing list creates a new outer list but does not recursively copy nested elements. More detailed construction and copying behavior is covered in the corresponding list lessons.

4. How a list relates to its elements#

A useful mental model is a sequence of slots containing references to Python objects. Each position identifies an element, and several positions may refer to the same object.

PYTHON
record = {'score': 10} items = [record, record] record['score'] = 20 print(items) print(items[0] is items[1])

Output:

[{'score': 20}, {'score': 20}]
True

The dictionary has not been copied twice. Both list positions refer to the same dictionary. Updating that dictionary through the name record is visible through either list position.

Loading diagram…

This model explains why lists can hold different object types without converting their elements to a common representation. It also explains why changing a nested mutable object can affect multiple parts of a program.

In CPython, an ordinary list is implemented using a resizable array of object references. The referenced Python objects need not occupy adjacent memory addresses. The language-level sequence contract does not require every Python implementation to use the same physical memory layout.

A list containing a million references to objects is not equivalent to a packed array of a million unboxed numbers. Memory consumption depends on the list's reference storage, the reachable objects and whether those objects are shared. For dense numeric workloads, consider a representation designed for that workload rather than assuming a Python list is the most compact option.

5. Mutability and object identity#

PYTHON
items = ['pen', 'book'] alias = items items[0] = 'pencil' items.append('bag') print(alias) print(items == ['pencil', 'book', 'bag'])

Output:

['pencil', 'book', 'bag']
True

The item assignment replaces one reference in the existing list. The append operation grows the same list. Because alias and items refer to the same outer list, both names observe the changes.

Loading diagram…

Assignment of a list to another name does not create a separate list. Mutation and rebinding are different operations: changing the existing object may affect aliases, while assigning a different object to one name does not change the object referenced by the other name.

The earlier mutability lesson explains shared references, shallow copies, deep copies and repeated nested lists in greater detail. The key lesson for using a list is to establish ownership before mutating it, especially when it was received from a caller.

6. Equality, membership and truth testing#

PYTHON
print([1, 2] == [2, 1]) print([1, 2] == [1, 2]) print(bool([]), bool([0])) print('book' in ['pen', 'book'])

Output:

False
True
False True
True

Ordinary list equality is sequence equality: lengths must match and corresponding elements must compare equal. The order matters. Equal lists need not be the same object.

The membership operator checks whether an element is present using the list's membership semantics. It is not a recursive search through arbitrary nested objects.

An empty list is falsey, and a nonempty list is truthy regardless of whether its individual elements are falsey. A list containing zero is still a nonempty collection.

Lists are unhashable. This is why they cannot directly serve as keys in ordinary dictionaries or as elements of ordinary sets. Use a hashable representation only when its semantics fit the requirement. A tuple of list elements is hashable only when its own elements satisfy the hashability requirement.

7. Practical example: accumulate matching records#

A list is a natural choice when the output must retain the encounter order of an unknown number of matching items.

PYTHON
def collect_active(records): active = [] for name, enabled in records: if enabled: active.append(name) return active print(collect_active([('Ada', True), ('Lin', False), ('Sam', True)])) print(collect_active([]))

Output:

['Ada', 'Sam']
[]

The function builds a new result list on every invocation. It walks the records once, appends names that satisfy the truth test, and returns the collected values in their original encounter order.

Repeated matching names would remain repeated in the output. If unique names are required, that is a different contract. A set or an order-preserving deduplication strategy may then be appropriate.

The example assumes every input record contains two unpackable values and that the second value is suitable for truth testing. It does not enforce a complete record schema or restrict that value to the bool type.

For n input records and k matches, the loop typically takes O(n) time under constant-cost record access and truth testing, and the result uses O(k) reference storage. It does not require an additional copy of the input collection.

8. Common list operations at a glance#

OperationExamplePurpose
Lengthlen(items)Number of elements
Indexingitems[0]Select an element
Slicingitems[1:3]Obtain a subsequence
Assignmentitems[0] = valueReplace an element
Appenditems.append(value)Add one element at the end
Extenditems.extend(values)Add elements from an iterable
Insertitems.insert(i, value)Add an element at a position
Removeitems.remove(value)Remove the first matching value
Popitems.pop()Remove and return the last element
Sortitems.sort()Reorder the existing list
Copyitems.copy()Create a shallow outer copy

These are an overview, not interchangeable operations. In particular, some methods change the existing list and return None, whereas others return an element or a new collection. Read the operation's contract before assigning its result to a variable.

Subsequent lessons address list construction, element access, slicing and these methods separately.

9. Performance and memory characteristics#

In CPython's conventional resizable-array cost model, ordinary lists support efficient random access and appending at the end.

OperationTypical complexity
len(items)O(1)
Read or replace a valid indexO(1)
Append one elementAmortized O(1)
Remove the final element with pop()Amortized O(1)
Insert or remove near the beginningO(n)
Linear membership searchO(n) element comparisons
Materialize a slice with k elementsO(k)
Iterate over n elementsO(n)

These estimates assume ordinary built-in lists and bounded-cost element operations. Equality checks can themselves be expensive for complex objects. The table is an implementation-oriented model rather than a guarantee of every interpreter's allocation strategy or latency.

Appending is amortized constant time because CPython generally reserves additional reference capacity when growing a list. A particular append can require resizing and moving reference storage. Thus an average-over-many-operations complexity claim is different from a worst-case latency guarantee for one operation.

Inserting at or removing from the beginning can require shifting many reference positions. If frequent operations at both ends are central to an application, collections.deque may be a better fit. If fast membership and uniqueness are the primary requirements, a set may be more suitable for hashable values.

The list stores all its references in memory. A generator or range can represent certain sequences without materializing all elements. Choose a list when random access, repeated traversal or mutation is necessary, not merely because a for loop is involved.

10. Choose the appropriate collection#

RequirementCollection to consider
Ordered, mutable sequence with duplicateslist
Fixed sequence of referencestuple
Unique hashable elements and membership checksset
Key-to-value lookupdict
Arithmetic progression of integersrange
Frequent operations at both endscollections.deque

There is no universally best collection. The useful question is which operations and invariants the application requires. A list can implement many behaviors, but other collection types can express the intended contract more clearly or avoid unnecessary work.

11. Failure modes and common mistakes#

ExpressionExpected exception
hash([1,2])TypeError: unhashable list
[][0]IndexError: no element at index zero
list(42)TypeError: integer is not iterable

These three expressions were independently executed and produced the stated exception classes.

Other mistakes include treating a list as a sorted or unique collection by default, assuming a second name is a copy, expecting type annotations to enforce element types, and materializing a huge iterable unnecessarily.

When an operation changes the contents of a shared list, consider whether the caller expects in-place mutation or a new result. When processing untrusted iterables, impose appropriate input and result limits.

Interview-ready answer#

A Python list is a built-in ordered, mutable and dynamically sized sequence of object references. It supports duplicates, heterogeneous objects, indexing, slicing and iteration. Lists can be constructed with square brackets or from an iterable using list(). Element assignment, append and other mutating operations can update an existing list, and aliases observe those changes. Lists are unhashable. CPython normally implements lists as resizable arrays of references, providing constant-time indexed access and amortized constant-time append, while operations that shift many positions can take linear time. Choose lists when order, positional access and mutation are important.

Official references#

Verification note: Six runnable Python example groups matched their expected outputs in independent namespaces on Python 3.13.5. Three independent expected-exception tests passed. A seeded suite of 500 randomized integer tuples checked list construction and preservation of the existing elements after append, for a total of 1,000 assertions. Two fenced Mermaid diagrams were manually reviewed; mmdc was not available locally, so parser-level validation and public-site rendering were not performed. Official references are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design