Knowing how to work with a list in Python is a vital skill you need to acquire if you want to become a successful programmer.
“People who want to appear clever rely on memory. People who want to get things done make lists.”
And what we want to do is teach you how to create lists in Python. If you are not familiar with basic terms such as “types of data” or “variables” in Python, the linked articles can help you out. Or, if you need to refresh your knowledge about Python applications, top IDEs for Python development, and the best Python libraries and frameworks you simply can’t go without, visit our Python Programming Guide.
What is a List?
Moreover, we’ll see that Python creates a friendly environment for dealing with lists. Assume we want to create a list called “Participants” that contains the names of John, Leila, Gregory, and Cate. We should follow the rules about creating a generic variable. But we should not forget two things: to place the strings within square brackets and to make sure we use quotation marks.
Precisely, these brackets indicate that the elements inside form a list and not some other type of sequence.
How to Extract Elements from a List in Python?
Like how we extract a letter from a string, we use the same technique here.
We write the name of the list, and in brackets, indicate the position corresponding to the name we are interested in. It is important that we don’t use parentheses or braces.
For instance, let’s extract the name of Leila. As programmers, we start counting from 0, so 1 should be the correct position!
For the sake of argument, in such a situation, a computer scientist might say you have accessed the list by indexing the value 1. This means you have extracted the second element in this list variable.
Is There Another Way to Extract Elements from a List in Python?
In addition, there is a way to get to the last element from a list in Python – start counting from the end towards the beginning. Then, we’d need the minus sign before the digit and we should not be thinking that we begin enumerating from 0 again! To obtain “Cate”, we have to write -1.
And to obtain “Gregory” we need -2.
How to Replace and Delete Items from a List in Python?
Now, let’s study a key feature of lists – replacing or deleting items in a list.
Replacing items in a list
Let’s assume Cate had to quit for some reason, but Maria replaced her. Here’s what we can do: access the value at position number 3, which currently refers to “Cate”, and assign it with the string “Maria”.
Deleting items in a list
Let’s take a look at another scenario: imagine that Gregory got a better offer somewhere else, so he quit as well. There is nobody to replace him, but we must adjust our list accordingly. The del keyword could deliver the required result. Type del, then correctly index Gregory’s position by typing “Participants 2”.
It is important to note is that deleting an element changes the indices of all successive elements. After removing Gregory, Maria’s position shifted one place to the left and is now in the second position. There is no element in the third position.
Useful Methods when Working with Lists
Think of the terms method and function as interchangeable, because in practice, methods work quite like functions. However, the technically correct term to use in this situation is “method”.
Here is the syntax that allows you to call ready-made built-in methods that you do not have to create on your own and can be used in Python directly.
The .append() Method
So, a new name, “Dwayne”, needs to be added to the “Participants” list and we’ll use a method called .append().
After the name of the object, which in this case is the “Participants” list, we’ll put a dot called a dot operator.
The dot operator allows you to call on or invoke a certain method. To call the method .append(), state its name, followed by parentheses.
To insert the name “Dwayne” in our list, we must put the string “Dwayne” in inverted commas between the parentheses.
Important: Remember this general structure, because we have to comply with it if we wish to call any existing method in Python.
The .extend() Method
Alternatively, the same result can be achieved by using the .extend() method. Let’s invite George and Catherine in our group. First, we have to invoke the .extend() method but this time, within the parentheses, we’ll have to add brackets. This is because we are going to extend the “Participants” list by adding a list (instead of a string) specified precisely in them.
Side note: The elements of lists in Python are directly treated as string values. Looking at the picture below, we can see the first participant in our list is John.
It was not necessary to put any quotation marks around the “Participants” element to do that.
The len() Function
Finally, the len() built-in function counts the number of elements in an object. For instance, if our word is “Dolphin”, this function tells us that it is composed of 7 letters.
More importantly, though, this same function can be applied to obtain the number of elements in a list. When applied to the list we have here, it shows us that the list entails six members.
The range() Function
When you go deeper into learning Python, you may need to randomize data points and lists with data points, and that’s when you’ll be able to use Python’s built-in range() function.
It can help us by creating a list of numbers.
Syntax of the Function
The syntax of the function is the following:
range(start, stop, step)
The start value will be the first number in the list. The stop value will be greater than the last value in the list. It is going to be equal to the last number + 1 (just classical Pythonic logic). The so-called step value represents the distance between every two consecutive values on the list.
Importance of Each Value in the range() Function
The stop value is a required input, while the start and step values are optional. If not provided, the start value will be automatically replaced with a 0, and the step value would be assumed to be equal to 1. You could also remember the stop value as most important, the start value as less important, and the step value as least important.
A Few Examples
For this reason, range(10) will provide a list of 10 elements, starting from 0, implied after not indicating a start value, and ending at the tenth consecutive number – 9.
In another cell, if we write range(3, 7), for instance, Python will accept 3 as a start value, and 7 as a stop value of the range. So, we’ll have 4 elements – 3, 4, 5, and 6.
To specify a step value in a range(), the other two arguments must be chosen as well. If we write range(1, 20, 2), we’ll obtain a list with all the odd numbers from 1 to 19 included. We will start with the number 1, and the list will end with number 19 (which equals the stop value 20 – 1), stating only the odd numbers.
Functions vs Methods
Observe how a built-in function takes the object “Participants” as an argument, while when we are calling built-in methods, they are applied to the “Participants” list with the help of the dot operator. The different syntax helps you distinguish between the two. If you want to understand the difference on a deeper level, feel free to check out the following article.
How to Slice a List in Python?
Moving onto another very important concept – slicing.
In the future, when working in Python, you’ll typically have to deal with data that is quite big. Many of the problems that must be solved will regard a tiny portion of the data, and in such cases, you can apply slicing.
An Example of Slicing a List in Python
Imagine you want to use the “Participants” list we saw earlier to obtain a second much smaller list that contains only two names – Leila and Maria. In Pythonic, that would mean to extract the elements from the first and second position.
To access these elements, we will write
The first number corresponds precisely to the first position of interest, while the second number is one position above the last position we need. In our case, 2 + 1 = 3.
What we just did is slice our Participants list to obtain a new one with the names Leila and Maria.
Slicing the Beginning of a List
Now let’s get the first two names from the list, John and Leila. In this case, we don’t need a number at the beginning, and we can start by typing a colon. So by typing
Slicing the End of a List
One way to obtain the last 2 elements would be to indicate the fourth position, corresponding to “George”, and leaving nothing after the colon. This would mean we will extract all the elements from the fourth position included at the end of our list.
Another way to obtain the same result would be to put a minus sign(-) in front of the number 2. Thus, Python will revert the direction of counting, starting from the end towards the beginning. We are asking for 2 elements:
The .index() Method
Assume you know “Maria” is in your list, but you don’t know her position. In other words, you’d like to obtain the index of the element “Maria” from the Participants list. We can simply call the .index() method and indicate the string variable of interest in parentheses.
How to Create a List of Lists?
Our goal will be to create a list, called “Bigger List”, which contains the “Participants” list, and a new one we will call “Newcomers”. Let the latter enclose the names of Joshua and Brittany.
All we need to do in the next cell is write the name of the variable “Bigger List” and cite within brackets the names of the lists we would like to include.
The .sort() Method
An important method that could order the names of our participants in alphabetical order is .sort().
As you can see in the picture above, after applying it to our list, Catherine comes first and Peter is last. If, within the brackets, we say we would like the names to be sorted in reverse order by stating “reverse = True”, Peter would be first and Catherine last.
The .sort() Method with Numbers
Naturally, if our elements were sheer numbers, instead of people’s names, this method would function without any problems.
Observe how, in the picture below, the numbers from 1 to 5 are sorted from the smallest to the largest.
And here – from the largest to the smallest.
What Are the Benefits of Using Lists in Python?
To sum up, whenever you need to store a number of elements from the same data type, you can use a list. There are plenty of methods which will help when working with a list in Python. For example, now you know how to add, replace, and delete elements and how to find their number and sort them. In fact, now that you have understood the concept of slicing, you know how to take certain elements from a list. If you want to embark on the journey of figuring out what’s the difference between lists and tuples, check out our tutorial on tuples!
If you’re enthusiastic about boosting your Python knowledge, check out our super practical tutorials!