Glossary

List

A list is Python's general-purpose ordered, mutable sequence type. Lists are created with square brackets ([1, 2, 3]) or the list() constructor, and they can hold objects of any type — including other lists. Because lists are mutable, you can append, insert, remove, sort, and reverse elements in place.

Common list operations include .append(x) (add to end), .extend(iterable) (add multiple items), .insert(i, x) (add at position), .pop(i) (remove and return by index), .remove(x) (remove first occurrence by value), and .sort() (sort in place). Lists support slicing (a[1:5]), negative indexing (a[-1]), concatenation (+), repetition (*), and iteration. The built-in len(), min(), max(), and sum() all work on lists.

Under the hood, CPython implements lists as dynamic arrays of pointers. Appending is amortised O(1) because the array over-allocates, but inserting or deleting at the beginning is O(n) because every element must shift. For frequent insertions or deletions at both ends, consider collections.deque. List comprehensions provide a concise and Pythonic way to create lists from existing iterables: [x**2 for x in range(10)].

Related terms: Mutable, Tuple, Comprehension

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.