Quest 1 β’ Lesson 3
π¦ Lists & Tuples
Store, organise, and manipulate collections of data β understand when to use lists vs tuples.
A list is a collection of items that can be changed (mutable). A tuple is like a list but cannot be changed (immutable). Both are fundamental for storing groups of data.
mixed = [10, "hello", True, 3.14]
print(fruits) # Output: ['apple', 'banana', 'cherry']
print(fruits[0]) # Output: apple
π§ List Basics
- Lists are created with
[ ](square brackets). - Items are indexed starting from
0β first item isfruits[0]. - You can store different data types in one list.
- π Previously: You learned about variables and data types in Lesson 1.2.
π οΈ Useful List Methods
π Tuples β Immutable Lists
Tuples are created with ( ) (parentheses). They cannot be changed after creation.
coordinates = (10, 20)
# days.append("Thu") would cause an error β tuples are immutable!
Use tuples for data that should never change (e.g., weekdays, fixed settings).
β οΈ Common Mistakes
β Trying to change a tuple:
Tuples are immutable β you cannot add, remove, or change items after creation.
days = ("Mon", "Tue")
days[0] = "Sun" # β TypeError: 'tuple' object does not support item assignment
β Forgetting that list indexing starts at 0:
The first item in a list or tuple is at index 0, not 1.
fruits = ["apple", "banana", "cherry"] print(fruits[1]) # "banana" β index 1 is the second item
π‘ Pro Tips
Use lists for data that changes β tuples for fixed data.
Use lists when you need to add, remove, or update items. Use tuples for fixed data like days of the week, coordinates, or configuration settings.
Use tuple unpacking for cleaner code.
You can unpack a tuple into multiple variables in one line.
coordinates = (10, 20) x, y = coordinates print(x) # 10 print(y) # 20
β¨ Challenge: Build a Shopping List
Create a list called shopping with 3 items. Then:
- Append a fourth item.
- Remove the second item.
- Print the final list.
shopping.append("butter")
shopping.remove("bread")
print(shopping) # ['milk', 'eggs', 'butter']
π What's Next?
After mastering lists and tuples, you're ready to learn:
- Lesson 1.4: Conditional Statements β β make decisions with if/elif/else.
- Lesson 1.5: Loops β β repeat actions with for and while.
- π Ultimate Python Guide β β the complete beginner's resource.
π€ Share This Lesson
Help others learn Python β share this lesson!
β€οΈ Support Free Education
This course is 100% free. If it helps you, consider buying me a coffee.
β Buy Me a Coffee