Victor Jeman - Frontend Architectv3.0
Python Fundamentals14 min

Lists: your digital backpack

Learn to work with lists in Python - how to store, access, and modify collections of elements.

What You'll Learn

  • Create lists and access their elements using indices
  • Add and remove elements from lists with append() and pop()
  • Traverse a list using a while loop
  • Use len() and type() to get information about lists

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.

What are lists

A list in Python is an ordered collection of elements. You create one using square brackets [] and separate the elements with commas:

Result:

text
['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:

text
[]

Accessing elements (indexing)

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:

text
Numb
Lose Yourself
Blinding Lights

If 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.

Negative indices

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:

text
Bad Guy
Uptown Funk

Adding elements (append)

A 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:

text
['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.

Removing elements (pop)

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:

text
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:

text
Removed: Yesterday
Playlist: ['Imagine', 'Let It Be']

List length (len)

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:

text
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:

The type() function

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:

text
<class 'list'>
<class 'str'>
<class 'int'>

type() is especially useful when you are debugging and not sure what kind of data a variable holds.

Traversing lists with while

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:

text
Now playing: Sultans of Swing
Now playing: Money for Nothing
Now playing: Walk of Life

Let's unpack what happens here:

  1. We start with index = 0 (the first element).
  2. As long as index is less than the length of the list, we keep going.
  3. We print the song at the current position with playlist[index].
  4. We increase index by 1 to move on to the next element.
  5. When 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:

text
#1 - Zombie
#2 - Linger
#3 - Dreams
#4 - Ode to My Family
#5 - Ridiculous Thoughts

We 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.

Exercise : Hero's inventory

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:

text
=== Inventory ===
1. Wooden Sword
2. Old Shield
3. HP Potion

Exercise : Pick up and drop items

Start 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.

Exercise : Loot after battle

After 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.

Exercise : Equipment system

The 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.

Exercise : Shopping list manager

Write 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".

Exercise : Playlist manager with favorites

Create 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.

Complete game code: Python Kingdom (Lesson 5)

Your game now has an inventory system! The hero can collect items, equip them, and drop them:

Test Your Knowledge

Check how well you understood the lesson with these 6 questions.

Question 1 of 6

What is the index of the first element in a list?