Imagine you have different values (for example numbers or strings) and you want to group them together. Python lists allow you to do that and provide methods and functions for adding elements, removing elements and a lot more…
In Python (and many other programming languages) you assign the value to a variable using the equal sign. Here is how I can assign the value 1 to the variable number.
number = 1
A variable of type list contains multiple values, so how can we assign multiple values to a single variable?
We use square brackets.
list_name = [element1, element2, element3]
Before you start reading, this video will also help you understand the concepts explained here:
Lists of Integers in Python
Let’s define a list of integers that contains the first numbers in the Fibonacci sequence:
fibonacci = [1,2,3,5,8]
To print the full list we use the print statement:
An index is used in lists to access each element of the list, the value of the index starts from zero and the highest value is the number of elements in the list minus one.
To print the value of an element in a list based on the index we use the following syntax
For instance, to print the first element of the fibonacci list we use:
And to print the last element:
And what happens if we refer to an element in the list using an index that is bigger than the biggest index allowed for that list?
Let’s try it:
print(fibonacci) Traceback (most recent call last): File "/opt/python/app.py", line 5, in <module> print(fibonacci) IndexError: list index out of range
We get an “index out of range” error back…
It tells us that the index we have used is out of the range of the indexes allowed in the fibonacci list, whose biggest index is 4.
Printing Part of a List (Slicing)
In Python we can also use the colon ( : ) to print part of a list (called slicing).
For example, if I want to print the first three elements of our list I can use:
print(fibonacci[:3]) [1, 2, 3]
And to print the last two elements:
print(fibonacci[3:]) [5, 8]
Negative indexes can be used as well. For example to print the last element of the list we can use:
Lists of Strings and Mixed Data Types in Python
Another example of list could contain only strings. Each string is delimited by single quotes:
animals = ['dog','cat','tiger','lion'] print(animals) ['dog', 'cat', 'tiger', 'lion']
So far we have seen two lists:
- One that contains only numbers.
- One that contains only strings.
Python’s flexibility allows also to create a list that is a mix of numbers and strings, like the one below:
elements = [‘tiger’, 8, 0.5]
In the list elements we have:
- One string (‘tiger’).
- One integer number (8).
- One float number (0.5).
That’s cool! This is not possible in other programming languages.
Let’s see what else Python allows to do…
I want to create a list that contains the three lists we have created so far:
new_list = [fibonacci, animals, elements] print(new_list) [[1, 2, 3, 5, 8], ['dog', 'cat', 'tiger', 'lion'], ['tiger', 8, 0.5]]
What else can you do with lists?
Methods and Functions for Lists in Python
Lists in Python are mutable, this means that you can apply different operations to a list, for example adding elements to it and removing elements from it.
Let’s say I want to add another number to the fibonacci list.
I can use the append method but how do I call it on the fibonacci list?
You will use the variable name (fibonacci) followed by a dot ( . ) followed by the method name, in this case append.
For example to add the next number of the fibonacci sequence to the fibonacci list we use:
fibonacci.append(13) print(fibonacci) [1, 2, 3, 5, 8, 13]
Another useful method is remove that allows to remove an element from a list based on its value. In this case we want to remove the number 3:
fibonacci.remove(3) print(fibonacci) [1, 2, 5, 8, 13]
And, what happens if we execute the same command again?
fibonacci.remove(3) Traceback (most recent call last): File "/opt/python/app.py", line 13, in <module> fibonacci.remove(3) ValueError: list.remove(x): x not in list
The command fails because the number 3 is not present in the list.
In this case we have removed an element of the list based on its value.
What if we want to remove an element based on its index?
We can use the pop method.
Let’s say we want to remove the element at index 1:
fibonacci.pop(1) print(fibonacci) [1, 5, 8, 13]
And do you know what happens if you execute the pop() method without any index?
I will leave it to you to try it 🙂
Adding Multiple Elements to a List And Other Useful Methods and Functions
Now let’s go back to the original fibonacci list:
fibonacci = [1,2,3,5,8]
We have seen how to add the next element in the Fibonacci sequence…
…and what if I want to add the next 3 elements to the sequence.
I will use the extend method that takes as argument another list:
fibonacci.extend([13, 21, 34]) print(fibonacci) [1, 2, 3, 5, 8, 13, 21, 34]
We will complete this tutorial with the len() function used in Python to get the number of elements in a list.
If we take the last fibonacci list we can see that it has 8 elements.
This is confirmed if we apply the len function to it.
Other useful functions are:
- min: calculates the smallest element in the list
- max: calculates the largest element in the list
- sum: calculates the sum of the elements in the list
Also, another common scenario when using lists is to calculate the sorted version of a numeric list. To do that Python provides the sort method.
Let’s define a numeric list whose elements are not sorted:
numbers = [3,45,2,31,21,12,45,100,1]
Here is the output of the sort method:
numbers.sort() print(numbers) [1, 2, 3, 12, 21, 31, 45, 45, 100]
In this tutorial you have learned the basics about lists in Python. You now know how to:
- Define a list of integers, strings and mixed types.
- Print part of a list.
- Add one or more elements to a list.
- Remove elements from a list.
- Calculate the number of elements in a list.
- Get the smallest element, the largest element and the sum of the elements in a list.
- Sort the elements of a list.
Who can give me some examples of lists? 🙂
A software engineer who wants to make a difference by teaching you how to code.