Loading...
Loading...
Store and access ordered collections of items
A list is an ordered collection of items. Instead of creating 10 separate variables (fruit1, fruit2, fruit3...), you put them all in one list. Lists are the most versatile and commonly used data structure in Python.
fruits = ["apple", "banana", "cherry", "date"]
# 0 1 2 3
# -4 -3 -2 -1
print(fruits[0]) # "apple" — index 0 is the FIRST item
print(fruits[-1]) # "date" — index -1 is the LAST item
print(len(fruits)) # 4 — total number of items| Part | What it means |
|---|---|
| `fruits = [...]` | Creates a list (square brackets) |
| `"apple"` | An item in the list (separated by commas) |
| `fruits[0]` | Accesses the item at index 0 (first position) |
| `fruits[-1]` | Access using negative index (counts from end) |
| `len(fruits)` | Returns the number of items |
Python lists are zero-indexed — the first item is at position 0, not 1.
colors = ["red", "green", "blue", "yellow"]
print(colors[0]) # red — 1st item
print(colors[1]) # green — 2nd item
print(colors[2]) # blue — 3rd item
print(colors[3]) # yellow — 4th item
print(colors[-1]) # yellow — last item (shorthand!)
print(colors[-2]) # blue — second to lastmixed = [42, "hello", 3.14, True, None] # Any type works
nested = [[1, 2], [3, 4]] # Lists inside lists!Lists are everywhere in programming:
| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| `colors = "red", "green", "blue"` | That creates a tuple (parentheses), not a list | `colors = ["red", "green", "blue"]` |
| `colors[1]` expecting "red" | Index 0 is the first item! | `colors[0]` for "red" |
| `fruits[len(fruits)]` | Index out of range — indexes go 0 to len-1 | `fruits[len(fruits) - 1]` or `fruits[-1]` |
| Forgetting commas between items | Syntax error | Separate items with commas |
Create a list called animals with three animals (strings). Then:
animals = ["cat", "dog", "bird"] print(animals[0]) print(animals[-1]) print(len(animals))