Lists
Our variables so far have only had one single value (at a given time), for example:
age = 25
height = 1.78
greeting = "Welcome to my home"
But, wait a minute, that variable greeting contains more than just one thing. It's a string containing four words, or 18 characters, in a row.
In the same way, could we store several numbers in the same variable? Yes!
Lists
In Python, we can store several pieces of information in a list. Other programming languages might have something called an "array".
We write a list within square brackets, [ and ], and every item (or element) is separated by a comma.
my_favorite_numbers = [4, 8, 15, 16, 23, 42]
We can also have a list with just one number:
short_list = [3]
Or, even an empty list.
empty_list = []
And this can actually be useful too. We will talk more about that in future sections, but first - let's see what we can do with lists.
Counting with lists
With a list, we can collect data that belongs together. Here's an example: Imagine we're running a small café and we've counted how much profit we've made each day for a week. We can collect that information in a list.
profit = [365, 123, 999, 100, 243, 12, 155]
We want to know how much we earned on the best and on the worst day. For that, there are built-in functions called min and max which are useful for lists.
print(min(profit))
print(max(profit))
How many days has the café been open?
That's like asking how many numbers are in the list, or indeed how "long" the list is. For that, we have a function called len (short for length):
print(len(profit))
And how much did we earn during the week as a whole?
That's the sum of all those numbers, and for that we have a function called sum:
print(sum(profit))
Average
Here's another question: What was the average income per day during the week?
Mathematics tells us that the average is the sum divided by the number of items. Now that we know that the sum and len functions exist, we can combine them:
Some of these functions also work on strings. For example:
name = input("What is your name? ")
number_of_characters = len(name)
print(f"Number of characters: {number_of_characters}")
Lists are one of the most important tools to collect data that belongs together. We can also add to and remove from lists. We will see more of that in the next section.
In this video, we look at how to randomly generate a color, even though it's not a number, using lists.
- Variable: A part of the computer's memory where we can store something, like a piece of text, a name, or a number.
- List: A list is a collection of data in order. Can also be known as "array" in other programming languages.
- Function: Small, reusable parts of our code, for example input, print, sum, len, min or max. Sometimes referred to as methods.