PythonPython ListsList indexing

How do you access elements in a list?

Question 78 of 88 · Updated

On this page

Use square brackets with an integer index to retrieve an element from a Python list. Indexing starts at zero, so items[0] selects the first element, and items[-1] selects the last. An index outside the valid range raises IndexError.

1. Access an element by position#

PYTHON
a = ['pen', 'book', 'bag'] assert (a[0], a[1], a[-1], a[-3]) == ('pen', 'book', 'bag', 'pen')

The expression a[1] retrieves the second element, not the first. Indexing returns the object at that position, without constructing a new list or copying the element. A list may contain any Python object, so the result may itself be another list, a dictionary, or a number.

Loading diagram…

Both index labels in each column select the same position. Negative indexing is relative to the end of the current list, not to the end of the list at the time it was created.

2. Understand valid index boundaries#

For a nonempty list of length n, the valid integer indices are -n through n-1 inclusive. A negative index i corresponds to position n+i. Python does not repeatedly wrap out-of-range indices around the list.

Expression for a three-element listResult
a[0]First element
a[2]Last element
a[-1]Last element
a[-3]First element
a[3]IndexError
a[-4]IndexError
a[1.0]TypeError
a['1']TypeError

An empty list has no valid element index, including zero and negative one. Integer-like objects implementing the index protocol can be accepted; a float is not accepted merely because its value is mathematically integral. Boolean values are technically valid indices because bool is a subclass of int, but using True or False as a position generally obscures intent.

3. Access nested elements#

PYTHON
assert [[10, 20], [30]][0][1] == 20

Python evaluates the first subscription to obtain the inner list, then evaluates the second subscription on that result. Each level must support the requested operation. Nested lists need not have equal lengths: validating an outer index does not validate an inner index.

For a matrix-like list, use rows[row_index][column_index], not rows[row_index, column_index]. The latter passes a tuple as the subscription key and is not supported by ordinary lists. Specialized array libraries may define different semantics.

4. Access multiple elements or traverse a list#

PYTHON
a = ['pen', 'book', 'bag'] assert a[1:3] == ['book', 'bag'] assert list(enumerate(a)) == [(0, 'pen'), (1, 'book'), (2, 'bag')]

A slice selects a subsequence and returns a new outer list containing references to the selected objects. Its stop position is excluded. Unlike single-element indexing, ordinary slice bounds can be clipped to the sequence limits. The next lesson covers slicing in detail.

When all values are required, prefer a direct for loop over the list. Use enumerate when both position and value matter. The membership operator answers whether a value is present; list.index(value) searches for the first matching position and raises ValueError when no match exists. Neither is a replacement for indexing when the position is already known.

5. Handle an optional position explicitly#

Sometimes the caller supplies an index that might not exist. A fallback helper is useful when absence is expected rather than a programming error.

PYTHON
import operator def get_at(items, index, default=None): index = operator.index(index) return items[index] if -len(items) <= index < len(items) else default a = ['pen', 'book', 'bag'] assert get_at(a, -1) == 'bag' assert get_at([], 0, 'missing') == 'missing' assert get_at([None], 0, 'missing') is None

The helper validates the index protocol before checking bounds, so invalid index types are not silently converted to missing values. It handles negative indices correctly and distinguishes a stored None from a missing position when a distinct default is supplied. In a real API where every possible stored value is allowed, a unique sentinel object can distinguish absence without reserving a particular string or None.

This helper assumes the list is not modified between the bounds check and retrieval. For concurrently mutated shared lists, use an appropriate synchronization or ownership strategy. In ordinary code where an invalid index indicates a bug, allow IndexError to surface rather than hiding it behind a fallback.

Loading diagram…

6. Performance and practical mistakes#

For an ordinary CPython list, retrieving a valid integer position is O(1) in the usual fixed-size index cost model because the list uses an array of references. Searching for a value may require O(n) comparisons. A slice containing k elements requires O(k) time and additional reference storage. Iterating over the entire list requires O(n) time, assuming constant-cost work per element. These are implementation-oriented complexity estimates, not universal guarantees about custom sequence classes or every interpreter.

Do not confuse a position with a value, use one-based positions without conversion, or assume that retrieving a mutable object produces a copy. If a list contains mutable records, retrieving one record and changing it changes that shared object. Also avoid using a previously cached index after insertions or removals unless the application guarantees that the position still identifies the intended item.

Interview-ready answer#

Python lists support zero-based indexing using square brackets. Positive indices start at zero, negative indices count backward from the end, and an invalid integer index raises IndexError. Indexing retrieves one existing object, slicing retrieves a new outer list of selected elements, and iteration is preferable when visiting every element. CPython lists provide constant-time positional access, unlike linear search by value.

Official references#

Verification: Python 3.13.5 executed the example assertions, four expected exception cases, and 2,650 boundary checks across list lengths zero through 49. Mermaid syntax was manually reviewed, not parser-tested. Official references are supplied under the authorized offline research exception; live documentation, Supabase changelog and public-site rendering were not checked.

References

  1. 1.
    Python tutorial: Listsdocs.python.org
  2. 2.
  3. 3.
    Subscriptionsdocs.python.org
  4. 4.
    operator.indexdocs.python.org
  5. 5.
    enumeratedocs.python.org

Related questions

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