🔍 Quick Lesson
Lists in Python are used to store multiple items in a single variable. Think of them like magical scrolls where you can keep your potions, ingredients, or spell names in one place!
1. Creating a List
potions = ["Healing", "Invisibility", "Strength"]
This creates a list called potions
with three elements.
2. Accessing Elements
Lists are ordered and can be indexed using numbers starting from 0:
print(potions[0]) # Outputs: Healing
Use negative numbers to start from the end: potions[-1]
gives Strength
.
3. Modifying Lists
You can update list items by accessing their index:
potions[1] = "Flying"
This changes the second item from "Invisibility" to "Flying".
4. List Methods
append()
– adds an item to the end:potions.append("Mana")
remove()
– removes a specific item:potions.remove("Strength")
insert()
– inserts an item at a specific index:potions.insert(1, "Speed")
len()
– returns the number of items:len(potions)
5. Looping Through a List
for potion in potions:
print(potion)
This will print each item in the potions
list.
6. Slicing Lists
Use slicing to access parts of a list:
potions[1:3]
Returns a new list with items at index 1 and 2.
7. Nested Lists
Lists can contain other lists (like having a scroll inside another scroll):
inventory = [["Sword", "Shield"], ["Potion", "Elixir"]]
inventory[0][1]
returns Shield
.