Collections: Don't Lose Your Data
So far, we've used variables to store one thing at a time. One name, one number, one boolean.
But what if you need to store 100 names? Creating name1, name2, name3... is a terrible idea.
Instead, we group them together into a Collection.
The humble List
A ListAn ordered collection of items. You create them using square brackets [ ].
is simply an ordered sequence of items. It uses square brackets [].
friends = ["Rahul", "Priya", "Amit"]
To get an item out of the list, you ask for its position (called an index). But beware: Python starts counting at 0, not 1!
fruits = ["Apple", "Banana", "Mango"] print(fruits[0]) # Prints Apple print(fruits[1]) # Prints Banana fruits.append("Orange") print(fruits)
Storing Key-Value Pairs
Lists are great, but sometimes numbers aren't the best way to look things up.
A DictionaryA collection of key-value pairs. You look up the 'key' to find its 'value'. Uses curly braces { }.
lets you use a name (a "key") to look up data (a "value"). It uses curly braces {}.
student = {
"name": "Sarpanch",
"age": 5,
"is_snake": True
}
print(student["name"]) # Prints Sarpanch
student["age"] = 6 # Happy birthday!
A List is like a shelf of numbered jars. You say "Give me jar number 0" or "Put this in the next available space at the end."
A Dictionary is like an actual contact book in your phone. You don't say "Call contact number 42." You say "Call 'Mom'." The Key is the name, the Value is the phone number.
Lists vs Dictionaries
The Address Book
book = {"Rahul": "123 Main St"}print(book["123 Main St"])You can look up the value using the key, but you can't look up the key using the value!
Collections in Action
Try adding and changing elements in the List and Dictionary.
- Use
.append()to add your own name to the end of theuserslist. - Print the 2nd user in the list (Careful! What index is the 2nd user?).
- Add a new key to the
profiledictionary for"hobby"and print the whole dictionary.
Grouping Stuff — Done! 📦
- Lists use
[]and store items in an ordered sequence. - Lists start counting at index 0. The first item is
my_list[0]. - You can add items to the end of a list using
.append("item"). - Dictionaries use
{}and store data in"key": "value"pairs. - You look up data in a dictionary using its key, like
my_dict["name"].