blog.dopana

Back

Welcome back, coder! 🎒

So far, our variables have been like single cardboard boxes that can only hold one thing at a time. But what if your game character is going on a big adventure and needs to carry a map, a health potion, and a shield? Creating separate variables like item1, item2, and item3 would be a mess!

Instead, we can give our robot a single Backpack that holds a whole list of items. In Python, this is called a List!

What is a List? (The Labeled Backpack)#

Think of a list as a backpack with numbered compartments (or slots) inside it.

  • The first slot is 0 (not 1!). In coding, we almost always start counting from zero.
  • The second slot is 1, the third is 2, and so on.
graph LR
    subgraph Backpack ["🎒 backpack = ['Map', 'Potion', 'Shield']"]
        Slot0["Slot [0]: 🗺️ Map"]
        Slot1["Slot [1]: 🧪 Potion"]
        Slot2["Slot [2]: 🛡️ Shield"]
    end

In Python, we write a list using square brackets [ ] and separate the items with commas:

backpack = ["Map", "Potion", "Shield"]
python

Accessing Items (Looking Inside the Slots)#

To ask the robot to pull an item out of a specific slot, we write the name of the list followed by the slot number in square brackets:

print(backpack[0])  # The robot prints "Map" 🗺️
print(backpack[2])  # The robot prints "Shield" 🛡️
python

If we ask for backpack[3], the robot will get confused and crash because there is no slot 3!

Managing Your Backpack (List Tricks)#

As the adventure goes on, our backpack contents will change. Here are three tricks to manage it:

1. Packing a New Item (append)#

To add a new item to the end of the list, use .append():

backpack.append("Sword")
print(backpack)  # Prints: ['Map', 'Potion', 'Shield', 'Sword'] ⚔️
python

2. Unpacking/Removing an Item (remove)#

To throw away an item, use .remove():

backpack.remove("Potion")
print(backpack)  # Prints: ['Map', 'Shield', 'Sword'] (The Potion is gone!)
python

3. Counting Your Items (len)#

To see how full your backpack is, ask Python to check its length using len():

print(len(backpack))  # The robot counts the items and prints 3
python

Try It Yourself! 🎮#

Open your Python playground and try this code adventure:

snacks = ["Apple", "Cookie"]
print("Original snacks:", snacks)

# 1. Pack a banana!
snacks.append("Banana")

# 2. Eat the cookie!
snacks.remove("Cookie")

# 3. Print the final list
print("Leftover snacks:", snacks)
print("Number of snacks left:", len(snacks))
python

Run the code to see if the robot correctly tells you what is left in your snack bag!

Next time, we will explore Turtle Graphics, where we will command a virtual turtle to draw colorful shapes on our screen. See you then!

References#