Learn to work with lists in Python - how to store, access, and modify collections of elements.
Imagine you have a backpack where you can toss in anything: books, keys, headphones, your phone. You can pull out whatever you want, add new stuff, and check what is inside at any time. Well, in Python there is something that works exactly like that, and it is called a list.
Up until now, you have been working with variables that store a single value, a number, a piece of text, a True or False. But what do you do when you want to keep multiple things together? For example, all the songs in your favorite playlist? You are not going to create a separate variable for each song. That would be chaos. Instead, you put them all in a list and you are done.
In this lesson, we are going to build a small playlist manager. We will learn how to create lists of songs, add new tracks, remove the ones we no longer like, and go through the entire playlist. Let's hit play.
Every hero needs a backpack. In this lesson you build the inventory system of the Python Kingdom using lists. The hero will be able to pick up items, drop them, and equip weapons and armor from the inventory for stat bonuses.
A list in Python is an ordered collection of elements. You create one using square brackets [] and separate the elements with commas:
Result:
['Bohemian Rhapsody', 'Stairway to Heaven', 'Hotel California']A list can contain any data type. You can have a list of numbers, a list of strings, or even a mix:
You can also create an empty list, like a playlist you just created but have not added anything to yet:
Result:
[]Every element in a list has a position called an index. And here comes the part that surprises everyone at first: indexing starts at 0, not at 1. The first element is at position 0, the second at position 1, and so on.
Think of it like an elevator that starts at the ground floor (floor 0), not at floor 1.
Result:
Numb
Lose Yourself
Blinding LightsIf you try to access an index that does not exist, Python will throw an IndexError. For example, if your list has 4 elements and you ask for playlist[10], Python does not know what to give you and gets upset.
Python has a very handy trick: you can use negative indices to access elements from the end of the list. Index -1 refers to the last element, -2 to the second-to-last, and so on.
This is super practical when you want to see what the last song in your playlist is without counting how many elements you have:
Result:
Bad Guy
Uptown FunkA static playlist is kind of boring. You want to add new songs as you discover them. For that, you use the append() method, which adds an element to the end of the list:
Result:
['Wonderwall', 'Creep']
['Wonderwall', 'Creep', 'Smells Like Teen Spirit']
['Wonderwall', 'Creep', 'Smells Like Teen Spirit', 'Come As You Are']Notice how each append() puts the new song at the tail of the list. It is like adding tracks to the end of a playlist on Spotify.
Sometimes you skip a song every time it comes on and decide it is time to remove it from the playlist. The pop() method removes the last element from the list and returns it, meaning it tells you what it took out:
Result:
Before: ['Imagine', 'Yesterday', 'Let It Be', 'Hey Jude']
Removed: Hey Jude
After: ['Imagine', 'Yesterday', 'Let It Be']You can also use pop() with a specific index to remove a song from a particular position:
Result:
Removed: Yesterday
Playlist: ['Imagine', 'Let It Be']When you want to know how many songs are in your playlist, you use the len() function. It returns the total number of elements in the list:
Result:
You have 5 songs in your playlist.len() is extremely useful when working with loops, as you will see shortly. It also helps you check whether a list is empty:
If you want to check what data type you have, you use the type() function. Applied to a list, it confirms that it is of type list:
Result:
<class 'list'>
<class 'str'>
<class 'int'>type() is especially useful when you are debugging and not sure what kind of data a variable holds.
Now comes the part that ties everything together: going through a list element by element. Using a while loop and a counter that starts at 0, you can go through every song in your playlist:
Result:
Now playing: Sultans of Swing
Now playing: Money for Nothing
Now playing: Walk of LifeLet's unpack what happens here:
index = 0 (the first element).index is less than the length of the list, we keep going.playlist[index].index by 1 to move on to the next element.index reaches len(playlist), the loop stops.Why do we use < and not <=? Because if the list has 3 elements, the indices are 0, 1, and 2. If we used <=, we would try to access index 3, which does not exist, and we would get an IndexError.
Let's do something more interesting, a playlist with track numbers:
Result:
#1 - Zombie
#2 - Linger
#3 - Dreams
#4 - Ode to My Family
#5 - Ridiculous ThoughtsWe used position + 1 in the display so that the numbers start from 1, not from 0, because normal people do not count from zero.
Lists are ordered collections of elements, indexed starting from 0. You use append() to add, pop() to remove, len() to count, and while to go through each element. With these tools you can manage any collection of data.
Create a list called inventory with 3 initial items: "Wooden Sword", "Old Shield", "HP Potion". Then, using a while loop, display each item preceded by its number (starting from 1).
Example output:
=== Inventory ===
1. Wooden Sword
2. Old Shield
3. HP PotionSET inventory = ["Wooden Sword", "Old Shield", "HP Potion"]
DISPLAY "=== Inventory ==="
SET i = 0
WHILE i < length(inventory):
DISPLAY (i + 1) + ". " + inventory[i]
i = i + 1Start with an empty inventory. Use append() to add 3 items found in a dungeon: "Golden Key", "Magic Scroll", "Blue Crystal". Display the inventory. Then use pop() to remove the last item and pop(0) to remove the first item. Display what you dropped and the final inventory.
SET inventory = [] (empty list)
inventory.add("Golden Key")
inventory.add("Magic Scroll")
inventory.add("Blue Crystal")
DISPLAY "Inventory:", inventory
SET dropped = inventory.remove_last()
DISPLAY "You dropped:", dropped
SET dropped = inventory.remove(position 0)
DISPLAY "You dropped:", dropped
DISPLAY "Final inventory:", inventoryAfter the hero defeats a monster, they find 3 items: "Fire Sword", "Rusty Armor", "Magic Ring". Display the found items with numbers. Ask the player to choose which item to keep (1, 2, or 3). Add the chosen item to the hero's inventory and display the updated inventory. If the player enters an invalid number, display an error message.
SET inventory = ["HP Potion"]
SET loot = ["Fire Sword", "Rusty Armor", "Magic Ring"]
DISPLAY "You found loot!"
FOR each item in loot (with number):
DISPLAY number + ". " + item
READ choice from user (converted to int)
IF choice >= 1 AND choice <= 3:
SET chosen_item = loot[choice - 1]
inventory.add(chosen_item)
DISPLAY "You took: " + chosen_item
ELSE:
DISPLAY "Invalid choice!"
DISPLAY "Inventory:", inventoryThe hero has an inventory with items and stat variables (attack, defense). Create the inventory with: "Fire Sword", "Iron Shield", "HP Potion", "Magic Ring". Display the inventory with numbers. Ask the player to choose an item to equip. If they choose "Fire Sword", add +10 to attack. If they choose "Iron Shield", add +7 to defense. Remove the equipped item from the inventory with pop() and display the updated stats and the remaining inventory.
SET inventory = ["Fire Sword", "Iron Shield", "HP Potion", "Magic Ring"]
SET attack = 20, defense = 10
DISPLAY inventory with numbers
READ choice (converted to int)
SET index = choice - 1
SET item = inventory[index]
IF item == "Fire Sword":
attack = attack + 10
DISPLAY "You equipped Fire Sword! +10 attack"
ELSE IF item == "Iron Shield":
defense = defense + 7
DISPLAY "You equipped Iron Shield! +7 defense"
ELSE:
DISPLAY "You cannot equip this item."
inventory.remove(index)
DISPLAY "Attack: {attack}, Defense: {defense}"
DISPLAY "Remaining inventory:", inventoryWrite a program that asks the user to enter products, one at a time. After each product is added, display how many products the list has. When the user types "stop", the program stops and displays the complete list.
Hint: use a while True loop and break when the user types "stop".
SET list = [] (empty list)
WHILE True:
READ product from user
IF product == "stop":
STOP loop
list.add(product)
DISPLAY "The list has " + length(list) + " products."
DISPLAY "Your list:", listCreate two lists: playlist with 5 songs and favorites empty. Traverse the playlist with a while loop and for each song ask the user if it is a favorite (yes/no). If yes, add it to the favorites list. At the end, display the favorites list and how many songs are in it.
SET playlist = ["Song1", "Song2", ...]
SET favorites = []
SET i = 0
WHILE i < length(playlist):
DISPLAY playlist[i]
READ answer ("yes" or "no")
IF answer == "yes":
favorites.add(playlist[i])
i = i + 1
DISPLAY "Favorites:", favorites
DISPLAY "Total:", length(favorites)Your game now has an inventory system! The hero can collect items, equip them, and drop them:
Check how well you understood the lesson with these 6 questions.