Victor Jeman Academy
Python Fundamentals10 min

Lists

Learn to work with lists in Python - how to create them, access elements by index, grow and shrink them, and walk through them by hand.

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

A list stores many values in one variable, in order, so you can add to them, pull from them, and walk through them one by one. Think of a backpack: you toss in books, keys, headphones, your phone, and you grab whatever you need later. Python lists work the same way.

So far your variables have held one value each: a number, a piece of text, a True or False. But what do you do when you want to keep a bunch of things together? Say, every song in your favorite playlist. You are not going to make a separate variable for each one. That is chaos. You drop them all in a list and you are done.

I will teach this with two examples on purpose: a playlist of songs and the hero's inventory. Same idea, two worlds. A playlist is just a list of songs; an inventory is just a list of items. Learn it once, use it everywhere.

So this lesson does double duty. You build a small playlist manager (create lists of songs, add tracks, drop the ones you skip every time, walk through the whole thing), and you build the inventory system of the Python Kingdom on top of the exact same moves. The hero picks up items, drops them, and equips weapons and armor for stat bonuses.

In this lesson, you will be able to:

  • Create a list with [] and reach any element by its index ([0] is the first)
  • Add to a list with the append() method and remove from it with pop()
  • Count a list with len() and check its type with type()
  • Walk through a list one element at a time with a while loop

What are lists

A list in Python is an ordered collection of elements (an element is just one item in the list). You create one using square brackets [] (the symbol that makes a list, and later reaches into one) 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)

Indexarea listelor
playlist = [...]
click pe un element ca sa vezi indexul

Every element in a list has a position called an index. Here is the part that trips up almost 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 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 lets you count from the end too. A negative index reaches in from the back: -1 is the last element, -2 the second-to-last, and so on.

That saves you from counting how many songs you have just to grab the last one:

Result:

text
Bad Guy
Uptown Funk

Adding elements (append)

append() si pop()
playlist (2 elemente)
[
0
"Wonderwall"
1
"Creep"
]
apasa append() ca sa adaugi melodii

A static playlist is kind of boring. You want to add new songs as you discover them. For that, you use the append() method. A method is a function that belongs to a specific thing; you call it by writing the thing, a dot, then the name, like playlist.append(...). (Compare len(playlist), name first, with playlist.append(...), thing first; that dot is the giveaway you are using a method.) append() 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']

Each append() drops the new song at the tail of the list, the same way a new track lands at the bottom of your playlist.

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.

You will lean on len() the moment you start looping, which is coming up in a minute. It also tells you when 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() earns its keep when you are debugging and you are not sure what kind of data a variable is actually holding.

Traversing lists with while

Here is the move that ties everything together: going through a list one element at a time. You already know while from the loops lesson, so put it to work. Start a counter at 0 and walk it up the list, song by song:

Result:

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

Here is what happens, step by step:

  1. You start with index = 0, the first element.
  2. As long as index is less than the length of the list, the loop keeps running.
  3. You print the song at the current position with playlist[index].
  4. You bump index up by 1 to move to the next element.
  5. When index hits len(playlist), the loop stops.

Why < and not <=? If the list has 3 elements, the valid indices are 0, 1, and 2. With <= you would reach for index 3, which does not exist, and Python hands you an IndexError.

This works, but counting the index by hand is a chore, and forgetting to bump it is a classic infinite-loop bug. A few lessons from now you meet for, a loop that walks the list for you with no counter to manage. For now, get comfortable with the manual version, because seeing the work makes the shortcut click later.

Now 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 display position + 1 so the numbers start at 1, not 0. Python counts from zero; the person reading the screen does not.

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.

Complete game code: Python Kingdom

Your game now has an inventory system. The hero collects items, equips them, and drops them:

Here is a thing worth noticing: append() and pop() are not the only ways to reshape a list. They always work at the end. Next lesson, in Lists, part 2, you slot an item exactly where you want it with insert(), and you ask a list for its smallest and largest value with min() and max(). Same backpack, a couple more tools.

And indexing with [0], [-1], and a while counter are not list-only tricks. A string is also a sequence of characters in order, with the same 0-based positions. A couple of lessons on, you point these exact moves at text, slicing a username apart to decode spells in the puzzle room.

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?