all Python 3Lists (list)term
List indexing
indexing/slicing
Access to an item by index. Negative indices count from the end. Assignment is supported.
Syntax
lst[i] | lst[i] = val
An out-of-range index raises IndexError right away — a list has no dict.get()-style fallback, so check len() first or catch the exception. lst[i] = val replaces an existing item only; it cannot grow the list, that is what append() and insert() are for. Indexing itself is O(1), whether you ask for the first item or the millionth.
Examples
lst = [10, 20, 30, 40, 50]
print(lst[0])
# → 10
print(lst[-1])
# → 50
print(lst[2])
# → 30
print(lst[-2])
# → 40
lst[1] = 99
print(lst)
# → [10, 99, 30, 40, 50]
lst[-1] = 0
print(lst)
# → [10, 99, 30, 40, 0]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy