What Is a List?
So far, your variables have held single values — one number, one string, one boolean. But what if you need to store a collection of items? That's where lists come in.
Creating Lists
A list is an ordered collection of items, written with square brackets:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
empty = []
Each item in the list has a position, and the list remembers the order you put things in. The first item is always at position 0 (we'll cover why in the next lesson).
Lists Can Hold Anything
Lists aren't picky about what they contain. You can store numbers, strings, booleans — even a mix:
mixed = [1, "hello", True, 3.14]
While mixing types is allowed, most real-world lists contain items of the same type — a list of usernames, a list of prices, a list of temperatures.
Lists Are Mutable
Unlike some data types, lists can change after you create them. You can add items, remove items, or change existing items. This flexibility makes lists incredibly useful for building up collections as your program runs.
shopping = ["milk", "bread"]
shopping.append("eggs") # Now: ["milk", "bread", "eggs"]
When to Use Lists
Lists are perfect when you have:
- Multiple items of the same kind: usernames, scores, file paths
- An ordered sequence: steps in a process, items in a queue
- A collection that might grow or shrink: search results, user selections
Lists vs Single Variables
Without lists, storing five usernames would require five separate variables:
user1 = "alice"
user2 = "bob"
user3 = "charlie"
user4 = "diana"
user5 = "eve"
With a list, it's one variable that holds all five:
users = ["alice", "bob", "charlie", "diana", "eve"]
This becomes essential when you don't know ahead of time how many items you'll have, or when you want to loop through all items with a single piece of code.