Quest 5: Lists - Collecting Treasures

Learn to Organize Multiple Items in Python

๐Ÿ“œ QUEST 5 | Difficulty: Beginner | Time: 5 minutes

๐Ÿ“Š Complexity Level: Beginner โญ

Perfect for students with no programming experience. This lesson introduces fundamental concepts that are essential for all programming. Great for college fair visitors and first-time coders!

๐Ÿ’ป Interactive Options:

  • ๐Ÿ““ Open in JupyterLite - Full Jupyter environment in your browser
  • โ–ถ๏ธ Run code directly below - All code cells on this page are editable and runnable
  • ๐Ÿ“ฅ Download Notebook - For use in local Jupyter or Google Colab

๐Ÿ“– Introduction: The Treasure Chest

Youโ€™re collecting items on your adventure: a sword, a shield, three health potions, a map, and a mysterious key. How do you keep track of everything?

You could use separate variables:

item1 = "sword"
item2 = "shield"
item3 = "health potion"
# This gets messy fast! ๐Ÿ˜ต

Or you could use a list - a single container that holds all your items in order!

๐ŸŽ’ Story Time: Think of a list like your adventure backpack. It holds multiple items, keeps them in order, and you can add or remove things as you go. You can even check whatโ€™s at specific positions, like โ€œWhatโ€™s in pocket number 3?โ€

๐Ÿ’ก Explanation: What are Lists?

A list is an ordered collection of items. Lists are: - Created with square brackets [] - Can hold different types of data - Items are ordered and indexed (starting from 0!) - Mutable (you can change them)

# Creating lists
inventory = ["sword", "shield", "potion"]
scores = [100, 95, 87, 92]
mixed = [1, "hello", True, 3.14]
empty = []

๐Ÿ“Š List Indexing:

Items in a list have positions (indices) starting from 0:

fruits = ["apple", "banana", "cherry", "date"]
#         0        1         2         3

Access items: Negative indices count from the end:

print(fruits[0])   # "apple"
print(fruits[2])   # "cherry"
print(fruits[-1])  # "date" (last item)
print(fruits[-2])  # "cherry" (second from end)

๐ŸŽฎ Activity: Manage Your Inventory

Letโ€™s create and manipulate an adventure inventory:

๐ŸŽฏ Challenge:

  1. Add a โ€œmagic wandโ€ to the inventory
  2. Remove the โ€œropeโ€ using inventory.remove("rope")
  3. Insert a โ€œcompassโ€ at position 1 using inventory.insert(1, "compass")
  4. Print the total number of items

๐Ÿ‘จโ€๐Ÿ’ป Code Example: List Operations

Lists have many useful methods and operations:

๐Ÿ’ก Common List Methods:

  • list.append(item) - Add item to end
  • list.remove(item) - Remove first occurrence
  • list.pop() - Remove and return last item
  • list.insert(index, item) - Insert at position
  • list.sort() - Sort the list in place
  • list.reverse() - Reverse the list in place
  • len(list) - Get number of items

๐Ÿงฉ Puzzle Time!

What will this code produce? Think through it, then run:

๐Ÿ”‘ Solution Explained:

The final list is: [5, 10, 20, 40, 50]

Step-by-step trace:

  1. Start: [10, 20, 30, 40, 50]

  2. After append(60): [10, 20, 30, 40, 50, 60]

    • Adds 60 to the end
  3. After insert(0, 5): [5, 10, 20, 30, 40, 50, 60]

    • Inserts 5 at position 0 (beginning)
  4. After remove(30): [5, 10, 20, 40, 50, 60]

    • Removes the first occurrence of 30
  5. After pop(): [5, 10, 20, 40, 50]

    • Removes the last item (60)

Key insight: Each method modifies the list in place. The order of operations matters!

๐ŸŽฎ Bonus: Slicing Lists

You can extract portions of a list using slicing:

๐ŸŽฏ Key Takeaways

โœจ Quest 5 Complete! โœจ

Youโ€™ve learned:

โœ… Lists store multiple items in order
โœ… Lists are indexed starting from 0
โœ… Use methods like append(), remove(), pop(), insert()
โœ… Access items with bracket notation: list[index]
โœ… Lists can be sliced, sorted, and reversed
โœ… Use len(), max(), min(), sum() for analysis

Next Quest: Ready to create reusable code? Try Quest 6: Functions!

๐Ÿš€ Try This at Home!

Create a to-do list manager:

# Simple to-do list
tasks = ["Learn Python", "Build a game", "Read a book"]

print("MY TO-DO LIST")
for i, task in enumerate(tasks, 1):
    print(f"{i}. {task}")

# Add new task
tasks.append("Practice coding")

# Mark a task as done (remove it)
completed = tasks.pop(0)
print(f"\nCompleted: {completed}")
print(f"Remaining: {tasks}")

Or make a high score tracker:

high_scores = [1500, 1200, 1000, 950, 800]
new_score = 1100

high_scores.append(new_score)
high_scores.sort(reverse=True)
high_scores = high_scores[:5]  # Keep only top 5

print("Top 5 High Scores:")
for rank, score in enumerate(high_scores, 1):
    print(f"{rank}. {score} points")

๐Ÿ“ฑ Excellent Progress! Lists are essential in almost every program. Master them! ๐Ÿ“‹