Python Lists
Python · Lists
Theory
A list is an ordered, mutable collection written with square brackets: sales = [100, 250, 300]. Ordered means every item has a position (index) starting at 0, so sales[0] is 100 and sales[-1], counting from the end, is 300. Mutable means you can change it after creation: sales[1] = 999 replaces an item, and append(), insert(), remove() and pop() grow or shrink it. A list can hold mixed types, even other lists.
Under the hood a list is a dynamic array of references to objects. Reading or replacing by index is very fast (O(1)), and append() is fast on average because Python over-allocates spare slots. Inserting or deleting near the front is slow (O(n)) because every later reference must shift. Since a list stores references, b = a does not copy it; both names share one list. Use a.copy() or a[:] for a shallow copy. Also beware [[0] * 3] * 3: it repeats a reference to the same inner list three times.
Why we use it
Most data arrives as a sequence of values: daily sales, customer names, rows from a file. A list keeps them in order, lets you reach any item by position, and can grow as new data comes in.
When to use it
Use a list for ordered data that may change. Use a tuple for fixed records, a set when you only care about unique items or fast membership, and a dict when you look values up by a key. For big numeric arrays, NumPy or pandas are faster.
How it works
- sales = [100, 250, 300] creates a list object
- Each slot stores a reference to an int object
- Accessing by index, e.g. sales[1]? Yes: Jump straight to that slot (fast). No: Use a method like append().
- sales.append(400) writes into a spare slot at the end
- The same list object is changed in place; no copy is made
- print(sales) shows [100, 250, 300, 400]
Syntax
my_list = [item1, item2, item3]Example
sales = [100, 250, 300]
sales.append(400)Key points
- Indexed from 0; -1 is the last item
- Support slicing: list[1:3]
- Mutable: items can be changed after creation
- b = a shares one list; use a.copy() for an independent copy
- Index access is O(1); inserting at the front is O(n)
- [[0] * 3] * 3 repeats the same inner list; use a comprehension instead