Lists are one of the main Python data types. They are very flexible due to the fact that multiple Python list methods are available to perform operations on lists.
What list methods are available in Python?
Some examples of methods for Python lists are append (adds an item to the end of the list), insert (adds an item at a specific position), remove (removes an item from the list), sort (sorts the list), index (returns the index of the first element with a given value).
In this tutorial we will go through multiple list methods to make sure you are comfortable when working with a Python list.
Let’s get started!
An Example of Python List
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 a 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 watch this video that will also help you understand the concepts explained here:
Also find out how to use the for loop in Python to go through the elements of a list. It’s something you will find useful after completing this tutorial.
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:
>>> print(fibonacci) [1,2,3,5,8]
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:
>>> print(fibonacci) 1
And to print the last element:
>>> print(fibonacci) 8
We can also use negative indexes to retrieve items starting from the end of the list.
So we can also retrieve the last element of the list using the -1 index:
>>> print(fibonacci[-1]) 8
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 list 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]
If you only specify the colon you will get back the full list.
>>> print(fibonacci[:]) [1, 2, 3, 5, 8]
This might not seem very useful but it’s a technique you can use to create a copy of a list.
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 we have:
- One string (‘tiger’).
- One integer number (8).
- One float number (0.5).
That’s cool! This is not possible in many 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?
List Methods and Functions 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.
Given the fibonacci list, let’s say I want to add another number at the end of the list.
I can use the append method.
The list append method adds an item at the end of a list.
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 list method is remove that removes 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]
As you can see we have removed the item from the list.
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 from the list based on its value.
What if we want to remove an element based on its index?
We can use the pop list method that removes and returns the element at a specific index.
Let’s say we want to remove the element at index 1:
>>> number = fibonacci.pop(1) >>> print(fibonacci) [1, 5, 8, 13] >>> print(number) 2
As you can see the number 2 is also returned by the pop method.
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 List 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]
The fibonacci list has been updated, the items in the list [13, 21, 34] have been added to the end of the fibonacci list.
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.
>>> print(len(fibonacci)) 8
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]
Another one of the list methods that can come handy is the list reverse method that reverses the elements of a list in place:
>>> numbers.reverse() >>> print(numbers) [1, 100, 45, 12, 21, 31, 2, 45, 3]
In this tutorial you have learned the basics about lists in Python and discovered several list methods available. 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.
Let me know if you have any questions 🙂
Get the full source code used for this tutorial to practice what you have learned.
A software engineer who wants to make a difference by teaching you how to code.