CODE WITH MARTIN

8. Lists


What Are Lists?

Lists are the first 'data structure' that Python and most other programming languages offer for dealing with data.

Lists are the next most useful thing after variables. We've seen how to use variables like integers and strings to handle numbers and text and now we're going to learn how we deal with lists of things.

The list is easily the most common data structure in Python and with this alone, you can go a long way with software programming without needing other types.

As developers, we need ways of dealing with a lot of information sometimes. Imagine programming a checkout experience for a web-site. A customer can shop around and add multiple items to their basket. The basket is holding a list of product items. Your software is most likely holding this list of products in a list.

Working With Lists

Let's dive right in and see how we define a list:

fruits = ["Apple", "Orange", "Banana"]
print(fruits)

The 'fruits' variable on line 1 is a new variable type, it isn't an integer, or a string, it is a list. Python knows that it is a list because to make a list, we start with the square bracket '['. We then have 3 strings all separated by commas, and we finish defining the list with the ending square bracket ']'. The 3 strings in brackets are the items that are added to the list. You can start your list with any number of items, or an empty list which would look like '[]' - an empty set of square brackets. You'll see when you run this code, the list is printed out in the terminal with all the items it contains.

Let's try adding more things to the list after we've defined it:

fruits = ["Apple", "Orange", "Banana"]
print(fruits)

fruits.append("Strawberry")
print(fruits)

Can you see on line 4 how we're using the variable 'fruits' to execute a function named 'append'? When we want to use functions inside of variables, we separate the function name we're executing and the variable name it's using with the dot '.' character. We'll learn more about this in a later section.

The append function accepts one parameter which can be any kind of value or variable name, which the append function then adds it to the list. You'll see the new list items being printed on line 5 with our new fruit string "Strawberry" added.

The 'append' function always adds your new item at the end of the list. But what about if we wanted to add to the beginning of the list? There's a function for that and it's called 'insert'. Let's see it in action:

fruits = ["Apple", "Orange", "Banana"]
print(fruits)

fruits.append("Strawberry")
print(fruits)

fruits.insert(0, "Kiwi")
print(fruits)

The 'insert' function on line 7 that we are executing, takes 2 parameters. The first is the index of where our item should be inserted to in the list. 0 is the value for the first item in the list, 1 would be the second, and so on. You'll see when the fruits are printed on line 8, the "Kiwi" fruit now appears at the start of the list.

Every item in the list has an index number and using an index number, we can retrieve the items in the list. Here's some code showing how we grab the items from the list using their index number:

fruits = ["Apple", "Orange", "Banana"]

print(fruits[0])
print(fruits[1])
print(fruits[2])

To retrieve an item from a list like we are doing on lines 3 to 5, you use the variable name of the list followed by a square bracket, the index number, and then a closing square bracket. The item from the list is then being passed to the print function as a parameter so we can print it to the terminal. You could store the value in a new variable if you wanted to, like so:

fruits = ["Apple", "Orange", "Banana"]

first_item = fruits[0]

print(first_item)

The variable we define on line 3 is being assigned to the first item from the list. The 'first_item' variable is a string variable type and this is because the item that we got from the list on line 3 is a string.

Using the index on a list, we can also set items in the list. Here's how:

fruits = ["Apple", "Orange", "Banana"]
print(fruits)

fruits[0] = "Mango"
print(fruits)

Line 4 in this code example is how we tell the list that we want to assign a new value to the item at index 0, which is the first item in the list. This replaces the "Apple" string that we started with in the list on line 1. Run the code to see.

How about removing items from the list? We can do this two ways. First, by index, and second, by a value that is contained in the list. Let's see how we can remove the "Orange" using its index:

fruits = ["Apple", "Orange", "Banana"]

fruits.pop(1)

print(fruits)

The 'pop' function on line 3 removes the item at the specified index number. Now let's try that again but removing by value:

fruits = ["Apple", "Orange", "Banana"]

fruits.remove("Orange")

print(fruits)

One important thing to remove with the 'remove' function on line 3 is that it only removes the first item it finds in the list. If there were two strings with the value "Orange" in the list, only the first one from the beginning of the list is removed.

Here's how we can clear a list using the 'clear' function:

fruits = ["Apple", "Orange", "Banana"]
print(fruits)

fruits.clear()
print(fruits)

We can sort a list using the 'sort' function:

fruits = ["Apple", "Orange", "Banana"]

fruits.sort()

print(fruits)

We can reverse the order of the list using the 'reverse' function:

fruits = ["Apple", "Orange", "Banana"]
print(fruits)

fruits.reverse()
print(fruits)

We can count the numbers of items in the list that have a specific value using the 'count' function:

fruits = ["Apple", "Orange", "Banana"]

oranges = fruits.count("Orange")

print(oranges)

We can get the index number of an item that has a specific value using the 'index' function:

fruits = ["Apple", "Orange", "Banana"]

orange_index = fruits.index("Orange")

print(orange_index)

If there are multiple items in the list with the same value, the 'index' function will only return the index of the first one it finds starting from the beginning of the list.

We can count the count the total number of items in a list using the 'len' function:

fruits = ["Apple", "Orange", "Banana"]

count = len(fruits)

print(count)

Notice how the 'len' function does not use the 'fruits' variable like the other examples above. Instead, it's a function that we execute and pass the variable containing our list as an argument.

Here's how we can add items from one list to another list using the 'extend' function:

fruits = ["Apple", "Orange", "Banana"]
more_fruits = ["Lemon", "Pineapple", "Mango"]

print(fruits)

fruits.extend(more_fruits)

print(fruits)

The 'extend' function on line 6 is executed with one argument which is our list variable 'more_fruits'. The items in the 'more_fruits' list are added to the end of the items in the 'fruits' list.

And finally, an important point to make about lists is that they can contain multiple types of items. Our lists up to now have just used strings for names of fruits but we easily add integers or float values to the list too, like so:

items = ["Apple", "Orange", "Banana", 5, 7, 1, 2.9, 100.45]
						
print(items)

This is why lists are powerful for managing data. We can add as many items as we want to them and manipulate the lists using all kinds of functions that we learned above.

Lists Containing Lists

You might have wondered, if a list can contain any kind of variable type, well, a list is a variable type, so, doesn't this mean that a list can also contain another list? You would be correct! This can go as deep as you want, a list of lists that contains lists of lists...but, that's not common at all, but very possible.

Here's an example of a list of lists, and I'll also show how you can format the list on new lines to make it more readable:

items = [
    1,
    5,
    10,
    [1, 2, 3],
    5,
    7,
    [1, 5, 7]
]
										
print(items)

The first thing to mention with this code example is that Python is absolutely fine with processing new-lines in the code when seperating list items inside the square brackets. So to make the code much easier to read, I've separated each list item on its own line.

On line 5 and line 8, we show how we're defining another list that gets set as an item in the 'items' list.

There are a couple of ways you can retrieve those sub-lists inside the 'items' list. The following code shows how:

items = [
    1,
    5,
    10,
    [1, 2, 3],
    5,
    7,
    [1, 5, 7]
]

# Access the sub-list directly.
print(items[3][0])
									
# Retrieve the sub-list and assign it to a new variable.
sublist = items[3]
print(sublist[0])

Line 12 is an interesting line here. Python evaluates the argument to the print function by first looking at the 'items[3]' part, which means we want the value of the item at index 3. Index 3 in the 'items' list is the list on line 5. As this item is a list, we know that we can retrieve items from a list type using square brackets, so immediately after 'items[3]' we add another set of square brackets to access the items in that retrieved list.

Lists are an important data structure to remember. Try and get comfortable working with them. We'll be using lists a lot in future sections.

What We Learned