In this article we will focus on a complete walk through of a Python list data structure.
Table of Contents
- What is a Python list
- How to create a Python list
- How to access an element from a Python list
- How to slice a Python list
- How to sort a Python list
- How to add items to a Python list
- How to remove items from a Python list
- How to change items in a Python list
- Conclusion
What is a Python list
A Python list is a sequence data type that allows us to combine several items in one comma-separated data instance.
A list can contain elements of the same or different data types and it is mutable, which means that we can alter the size and content of a list object in Python.
How to create a Python list
Creating a list in Python is very straightforward. You need to put all the items separated by commas into square brackets.
Keep in mind that you can put different data types together, so integers, floats, booleans and even other lists.
Here are a few examples:
List with string elements
my_list = ['Apple', 'Banana', 'Orange', 'Pineapple']
print(my_list)
Output:
['Apple', 'Banana', 'Orange', 'Pineapple']
List with integer elements
my_list = [1, 2, 3, 4]
print(my_list)
Output:
[1, 2, 3, 4]
List with mixed type elements
my_list = ['Apple', 1, True, 2.4]
print(my_list)
Output:
['Apple', 1, True, 2.4]
List with nested elements
In the examples above each item in a list only contained one value.
What if we want to store two values per item? Python lists allow us to do that too!
For example, you would like to make a list of products and their prices. Your data is the following: price of an apple is $1 and price of a banana is $0.70.
In order to add two or more values per item in a list, we need to put them in square brackets and separate with commas.
It will look like having a list inside of a list (nested):
my_list = [['Apple', 1], ['Banana', 0.70]]
print(my_list)
Output:
[['Apple', 1], ['Banana', 0.7]]
How to access an element from a Python list
An important and very useful property of a Python list is that it’s an indexed sequence, meaning for a list with n elements, the first element will have an index = 0, second element index = 1, and all the way to n-1.
Access element from a list using index
An elements in a list can be accessed by its index and index can also be reversed meaning that the fist element will have an index = –n, second element index = –n+1, and all the way to -1.
To make it easier to showcase, take a look at the visualization below:
$$ \begin{matrix} \begin{array}{c|cccc} \hline \text{Index} & 0 & 1 & 2 & 3 \\ \text{List} & Apple & Banana & Orange & Pineapple \\ \text{Reversed Index} & -4 & -3 & -2 & -1 \\ \hline \end{array} \end{matrix} $$ $$\text{Length = n = 4}$$We can see that ‘Apple’ element in the list has two indexes: 0 and -4.
Let’s recreate this list in Python:
my_list = ['Apple', 'Banana', 'Orange', 'Pineapple']
Now, we would like to print out the first element from the list.
We know from before, that it has two indexes: 0 and -4, so we can try both and see if the output will be the same.
print(my_list[0])
print(my_list[-4])
In both cases, the output will be the same.
Output:
Apple
Apple
Find element in a list
Let’s assume we have the following list with string elements:
my_list = ['Apple', 'Banana', 'Orange', 'Pineapple']
print(my_list)
Output:
['Apple', 'Banana', 'Orange', 'Pineapple']
And you would like to fine the index of “Banana” element.
This can be simply found by using .index() method that takes some value as a parameter and finds its index in a Python list:
element = 'Banana'
element_index = my_list.index(element)
print(element_index)
Output:
1
We quickly found that the “Banana” element is located at index 1 of our list.
How to slice a Python list
In the section before we showed how you can access an element from a Python list using its exact index.
In this section we will show what to do when you want to access a range of elements, for example, first two or last two.
Recall that for retrieving items from a list using an index, we placed it in square brackets [].
Slicing is using the same approach, but instead of passing a single index value, we will pass a range.
A range in Python is passed using the following syntax [from : to].
Slicing without specifying from and to
If you don’t put any index into from and to, by default Python will take the entire list.
The following two lines of code produce an identical output:
print(my_list)
print(my_list[:])
Output:
['Apple', 'Banana', 'Orange', 'Pineapple']
['Apple', 'Banana', 'Orange', 'Pineapple']
Slicing with specifying from
You can slice a list with just specifying from and what it will take is the elements from the index you specified until the end of the list.
For example, you would like to print the last two elements in the list. Remember that you can use both index and reverse index.
The following two lines of code produce an identical output:
print(my_list[2:])
print(my_list[-2:])
Output:
['Orange', 'Pineapple']
['Orange', 'Pineapple']
Slicing with specifying to
You can slice a list with just specifying to and what it will take is the items from the beginning on the list until the element at the index you specified -1.
For example, you would like to print the first two elements of the list. Remember that you can use both index and reverse index.
The following code will produce the desired output:
print(my_list[:2])
Output:
['Apple', 'Banana']
Notice here, that we specified our to index = 2, what’s important to keep in mind is that index = 3 is actually the position of the third element. The way list slicing work in Python is that it goes through elements until the specified to index (in our case 2) and includes all elements up to that index but not including the element under the to index.
How to sort a Python list
Lists in Python have a method .sort() which allows us to sort the items in the list. In case your list contains strings, this method will sort it in ascending alphabetical order. If your list contains numerical values (integers or floats) it will sort it in ascending order. Please note that if you have a list will multiple data types, .sort() method won’t work and will produce an error. Let’s take a look at a few examples:
Sorting a list with strings
my_list = ['Apple', 'Orange', 'Banana', 'Pineapples']
my_list.sort()
print(my_list)
Output:
['Apple', 'Banana', 'Orange', 'Pineapples']
Sorting a list with numerical values
my_list = [1, 4, 2, 3]
my_list.sort()
print(my_list)
Output:
[1, 2, 3, 4]
In both cases we created unordered lists and after applying .sort() method, when printing out the list, it’s sorted.
How to add items to a Python list
In this section we will cover how to add new items to an existing list. There are two list methods that will help us with this: .append() and .insert(). They both can add new items to a list, but have a major difference: .append() adds items at the end of the list by “appending” them, whereas .insert() allows us to choose a specific “position” (index) in the list where the new item will be added.
Let’s work through some examples:
Appending items to a list
my_list = ['Apple', 'Banana', 'Orange', 'Pineapple']
new_item = 'Mango'
my_list.append(new_item)
print(my_list)
Output:
['Apple', 'Banana', 'Orange', 'Pineapple', 'Mango']
We started with our old list with 4 items (fruit). Now we want to add ‘Mango’ to our list. We create a variable new_item and assign ‘Mango’ to it. Then we append it to our main list and when we print it out, we see all 5 items in the list.
Inserting items into a list
The fundamental difference from the above approach is that in this case we are able to choose the exact position in the list where we want to insert the new item. This list method has the following syntax: .insert(index, item).
For example, our new item is ‘Mango’ and we would like to add it right after ‘Apple’ in the list. Knowing that the index (position) of ‘Apple’ item is 0, we should use index = 1 to add an item right after it.
Here is the code that will produce the output we are looking for:
my_list = ['Apple', 'Banana', 'Orange', 'Pineapple']
new_item = 'Mango'
my_list.insert(1, new_item)
print(my_list)
Output:
['Apple', 'Mango', 'Banana', 'Orange', 'Pineapple']
Perfect! ‘Mango’ was added/inserted right after ‘Apple’ using the correct index.
How to remove items from a Python list
In this section we will cover how to remove new items from an existing list. There are two list methods that will help us with this: .remove() and .pop(). They both can remove items from a list, but have a major difference: .remove() removes items that you specify (there has to be an exact match), whereas .pop() allows us to choose a specific “position” (index) in the list of the item you want to remove.
Let’s work through some examples:
Removing items from a list using values
my_list = ['Apple', 'Banana', 'Orange', 'Pineapple']
to_remove = 'Banana'
my_list.remove(to_remove)
print(my_list)
Output:
['Apple', 'Orange', 'Pineapple']
We started with our old list with 4 items (fruit). Now we want to remove ‘Banana’ from our list. We create a variable to_remove and assign ‘Banana’ to it. Then we remove it from our main list and when we print it out, we see the remaining 3 items.
Removing items from a list using index
The difference from the above approach is that instead of specifying a value of an item we are able to choose the exact position of an item you want to remove from a list. This list method has the following syntax: .pop(index). For example, you wan to remove ‘Banana’ from a list. Knowing that the index (position) of ‘Banana’ item is 1, we should use index = 1 to remove it from the list.
The default value for index is -1, meaning that if you don’t specify an index and just apply .pop(), it will remove the last item in the list.
Here is the code that will produce the output we are looking for:
my_list = ['Apple', 'Banana', 'Orange', 'Pineapple']
my_list.pop(1)
print(my_list)
Output:
'Banana'
['Apple', 'Orange', 'Pineapple']
How to change items in a Python list
In this section we will show how to change an item in a list. For example, you have an existing list of items, and you want to replace one of them with a new item. How do we do it?
In Python it’s really simple. All we need to do is specify the index of an item in a list that we want to change and then assign a new value to it.
Recall our list: Apple, Banana, Orange, Pineapple. Now, you want to replace Orange (index = 2) with Melon. Here is how to do it:
my_list = ['Apple', 'Banana', 'Orange', 'Pineapple']
my_list[2] = 'Melon'
print(my_list)
Output:
['Apple', 'Banana', 'Melon', 'Pineapple']
Conclusion
This article is an introductory walkthrough of Python list data structure and its methods which are important to learn as they are used in many areas of programming and in machine learning.
Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Data Structures articles.