🎒 Python Lists: Your Digital Backpack
Imagine you have a magical backpack. You can put anything inside—toys, snacks, books, even your pet rock! Python lists work exactly the same way. They’re containers that hold stuff for you.
🎯 What You’ll Learn
- How to create your own list (backpack)
- How to grab specific items from it
- How to change what’s inside
- How to check if something is there
- How to count how many things you have
📦 List Creation: Making Your Backpack
Creating a list is like getting a new backpack and deciding what to put inside.
The Magic Formula
my_list = [item1, item2, item3]
Square brackets [ ] are like the zipper of your backpack. Everything inside belongs together!
Examples
A backpack with fruits:
fruits = ["apple", "banana", "cherry"]
A backpack with numbers:
scores = [100, 85, 92, 78]
An empty backpack (ready to fill later):
empty_bag = []
A mixed backpack (Python doesn’t care!):
mixed = ["hello", 42, True, 3.14]
đź§ Remember This
- Use square brackets
[ ] - Separate items with commas
, - Items can be anything—numbers, words, even other lists!
🔢 List Indexing: Finding Your Stuff
Your backpack has pockets numbered starting from 0 (not 1!). To grab something, just say which pocket number.
graph TD A["fruits = ['apple', 'banana', 'cherry']"] --> B["Index 0: apple"] A --> C["Index 1: banana"] A --> D["Index 2: cherry"]
Getting One Item
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherry
Negative Numbers: Counting Backwards!
What if you want the last item but don’t know how many things are in the bag?
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # cherry (last)
print(fruits[-2]) # banana (second last)
-1 means “start from the end.”
✂️ List Slicing: Grabbing Multiple Items
Slicing is like saying, “Give me items from pocket A to pocket B.”
The Slice Formula
my_list[start:stop]
- start = where to begin (included)
- stop = where to end (NOT included)
Examples
letters = ["a", "b", "c", "d", "e"]
print(letters[1:4]) # ['b', 'c', 'd']
print(letters[:3]) # ['a', 'b', 'c']
print(letters[2:]) # ['c', 'd', 'e']
print(letters[:]) # ['a', 'b', 'c', 'd', 'e']
🎯 Quick Rules
| Slice | Meaning |
|---|---|
[1:4] |
From index 1 up to (not including) 4 |
[:3] |
From the start up to index 3 |
[2:] |
From index 2 to the end |
[:] |
Everything (a copy) |
🔄 List Mutability: Changing What’s Inside
Here’s something special about lists: you can change them!
This is called being mutable (changeable).
Swap One Item
colors = ["red", "green", "blue"]
colors[1] = "yellow"
print(colors) # ['red', 'yellow', 'blue']
You just replaced “green” with “yellow”!
Change Multiple Items
numbers = [1, 2, 3, 4, 5]
numbers[1:4] = [20, 30, 40]
print(numbers) # [1, 20, 30, 40, 5]
đź’ˇ Why This Matters
- Strings are immutable (can’t change individual letters)
- Lists are mutable (can change anything!)
# This works:
my_list = [1, 2, 3]
my_list[0] = 99
# This does NOT work:
my_string = "hello"
my_string[0] = "H" # ERROR!
🔍 Checking Element Existence: Is It There?
Before reaching into your backpack, you might want to check if something is actually inside. Use the magic word: in
The Simple Check
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes! We have banana!")
# Output: Yes! We have banana!
Checking What’s NOT There
fruits = ["apple", "banana", "cherry"]
if "mango" not in fruits:
print("Sorry, no mango today")
# Output: Sorry, no mango today
🎮 Real Example
allowed_users = ["alice", "bob", "charlie"]
username = "bob"
if username in allowed_users:
print("Welcome!")
else:
print("Access denied!")
# Output: Welcome!
📏 List Length: Counting Your Items
How many things are in your backpack? Use len() to find out!
Basic Counting
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3
Why This Is Useful
Looping through all items:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(f"Item {i}: {fruits[i]}")
Finding the last index:
fruits = ["apple", "banana", "cherry"]
last_index = len(fruits) - 1
print(fruits[last_index]) # cherry
Checking if list is empty:
my_list = []
if len(my_list) == 0:
print("The backpack is empty!")
🎯 Putting It All Together
Let’s use everything we learned in one story!
# Create a shopping list
shopping = ["milk", "eggs", "bread"]
# Check how many items
print(f"Items to buy: {len(shopping)}")
# Add something? First check if it exists
if "butter" not in shopping:
shopping.append("butter")
# Get the first and last items
first = shopping[0]
last = shopping[-1]
# Change the second item
shopping[1] = "cheese"
# Get items 1-3
middle_items = shopping[1:3]
print(shopping)
# ['milk', 'cheese', 'bread', 'butter']
🌟 Key Takeaways
| Concept | What It Does | Example |
|---|---|---|
| Creation | Make a new list | [1, 2, 3] |
| Indexing | Get one item | my_list[0] |
| Slicing | Get multiple items | my_list[1:3] |
| Mutability | Change items | my_list[0] = "new" |
| Existence | Check if inside | "x" in my_list |
| Length | Count items | len(my_list) |
🚀 You Did It!
You now understand Python lists—your digital backpack for storing anything you need. Go build something amazing!