Python Lists: The Definitive Guide for Working With Ordered Collections of Data
When programming, we always have to deal with data structures. What I mean is that we need to store information somewhere so that we can reuse it later.
Python is a very flexible programming language and gives us the possibility to use different types of data structures.
In this article, we'll analyze Python lists. So, if you're a beginner in Python and are searching for a comprehensive guide on lists, then this article is definitely for you.
Here's what you'll learn here:
Table of Contents:
What is a list in Python?
The top 9 features in Python lists, with examples
How to create a list in Python
Accessing list elements
Modifying the elements of a list
Adding elements to a list
Removing elements from a list
Concatenating lists
Calculating the lenght of a list
Sorting the elements of a list
List comprehension
What is a list in Python?
In Python, a list is a built-in data structure that allows us to store and manipulate data in the form of text or numbers.
Lists store data in an ordered way, meaning that the elements of a list can be accessed by their position.
Lists are also a modifiable kind of data structure, as opposed to tuples.
Finally, lists can also store duplicated values without raising errors.
The top 9 features in Python lists, with examples
The best way to learn Python is by putting our fingers on the keyboard and, possibly, solving an actual problem.
So, now we'll show the 9 top features of Python lists with code examples because, as we'll see, theory doesn't have much sense in programming: we just need to code and solve problems.
How to create a list in Python
To create a list, we need to use square brackets:
# Create a simple list
numbers = [1,2,3,"dog","cat"]
# Show list
print(numbers)
>>>
[1, 2, 3, 'dog', 'cat']
Another way to create a list is by using the built-in method list
. For example, suppose we want to create a list of numbers ranging from 0 to 9. We can use the built-in method range
to create the range, then we can pass it as an argument to the method list
to create the list like so:
# Create a list in the range
list_range = list(range(10))
# Show list
print(range_list)
>>>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Also, we can create the so-called list of lists that are nothing more than nested lists. For example, suppose we want to store the data related to measured times, in seconds, of people running. If we need these data as a list we can create a list of lists like so:
# Create a list of lists
times = [["Jhon"], [23, 15, 18], ["Karen"], [17, 19, 15],
["Tom"], [21, 19, 25]]
# Print list
print(times)
>>>
[['Jhon'], [23, 15, 18], ['Karen'], [17, 19, 15], ['Tom'], [21, 19, 25]]
Accessing list elements
The elements of a list can be accessed by their positions. What we need to remember is that in Python we start counting from 0. This means that the first element is accessed with a 0:
# Create a list of elements
values = [1,2,3,"dog","cat"]
# Print elements by accessing them
print(f"The first element is: {values[0]}")
print(f"The fourth element is: {values[3]}")
>>>
The first element is: 1
The fourth element is: dog
So, we just need to take care to make the right counting.
Accessing a list of lists is a little bit more complicated, but is not hard. We first need to access the position related to the external list, then we count in the internal one.
As we've said, practice is better than theory in Python. So, let's show this concept with an example:
# Create a list of lists
times = [["Jhon"], [23, 15, 18], ["Karen"], [17, 19, 15],
["Tom"], [21, 19, 25]]
# Print
print(f"The first runner is:{times[0]}.nHis first registered time is:{times[1][0]}nThe min registered time is:{min(times[1])}")
>>>
The first runner is:['Jhon'].
His first registered time is:23
The min registered time is:15
Jhon is the first registered runner, so we access it with times[0]
.
Then, we want to calculate his first registered time. To do so, we have to type times[1][0]
because: [1]
refers to the second position, with respect to the external list. Meaning that we've accessed the internal list [23, 15, 18]
. Finally, the [0]
accesses the first number of the internal list which, indeed, is 23.
Modifying the elements of a list
As we've said, lists are modifiable and to modify an element of a list we need to access it.
So, let's make an example:
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]
# Modify the third element
numbers[2] = 10
# Print new list
print(numbers)
>>>
[1, 2, 10, 4, 5]
So, in this case, we've modified the third element changing it from 3 to 10.
But we can also modify text. In particular, sentences. Let's see an example:
# Create a sentence in a list
sentence = list("Hello, World!")
# Substitute "world" with "Python"
sentence[7:] = list("Python!")
# Print sentence
print(''.join(sentence))
>>>
"Hello, Python!"
So, here we've substituted all the letters in our list "sentence" from the seventh (make the count start from 0, as we've said before) element to the last one with sentence[7:]
.
We've, then, used the method ''.join(sentence)
to print the sentence as a whole one. In fact, if we'd just used print()
it would print the letters as single elements like so:
print(sentence)
>>>
['H', 'e', 'l', 'l', 'o', ',', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!']
Adding elements to a list
Since lists are mutable, we can add new elements to them, if we need it and we have a couple of methods to do so.
The first one is to use the append()
method which is particularly suitable if we need to add just one element to a list. For example:
# Create a list with fruits
fruits = ['apple', 'banana']
# Append the element "orange" to the list
fruits.append('orange')
# Print list
print(fruits)
>>>
['apple', 'banana', 'orange']
Another way to add elements to an existing list is by using the extend()
method which is particularly suitable if we need to append more than one element at a time. For example, like so:
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]
# Extend the list with new numbers
numbers.extend([6, 7, 8])
# Print list
print(numbers)
>>>
[1, 2, 3, 4, 5, 6, 7, 8]
Removing elements from a list
Thanks to mutability, we can add elements to a list but we can even remove elements.
Also here, we have two ways to do so: we can use the slicing possibility or we can directly specify an element to delete.
Let's see these with Python examples:
# Create a list with fruits
fruits = ['apple', 'banana', 'orange']
# Remove the element banana
fruits.remove('banana')
# Print list
print(fruits)
>>>
['apple', 'orange']
So, the remove()
method gives us the possibility to directly delete a specific element from a list by typing its value.
The other method we can use is to access the position of the element we want to remove like so:
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]
# Delete on element: slicing method
popped_element = numbers.pop(2)
# Print
print(numbers)
print(f"The deleted element is:{popped_element}")
>>>
[1, 2, 4, 5]
The deleted element is:3
So, the pop()
method removes an element from a list by accessing its index.
Which one to use? It depends on the situation. If we have a very long list, it's generally a good idea to use the remove()
method so that we directly write the element we actually want to remove, and we don't make mistakes in counting the indexes.
Concatenating lists
The mutability of lists gives us the possibility to perform numerous tasks, like concatenating multiple lists together in one single list.
This operation is simple and is performed with a +
like so:
# Create a list
list1 = [1, 2, 3]
# Create a second list
list2 = [4, 5, 6]
# Concatenate list
combined_list = list1 + list2
# Print cncatenated lists
print(combined_list)
>>>
[1, 2, 3, 4, 5, 6]
This feature can, of course, be performed even with strings:
# Create a list
hello = ["Hello"]
# Create another list
world = ["world"]
# Concatenate
single_list = hello + world
# Print concatenated
print(single_list)
>>>
['Hello', 'world']
Another way to concatenate lists is to flatten a list of lists. In other words, we can create a single "straight" list from a nested list like so:
# Create a nested list
lists = [[1, 2], [3, 4], [5, 6]]
# Create a unique list
flattened_list = sum(lists, [])
# Print unique list
print(flattened_list)
>>>
[1, 2, 3, 4, 5, 6]
So, basically, we've used the sum()
method to get all the elements of the list lists
and appended them to an empty list with []
.
Calculating the length of a list
In the previous examples, we've created lists ourselves to make Python examples about how to manipulate lists.
However, when working with Python, it often happens that we retrieve data from different sources, meaning someone created a list we actually don't know anything about.
The first thing we'd better do when we are in front of an unknown list is to calculate its length. We can do it like so:
# Create a list
fruits = ['apple', 'banana', 'orange']
# Print list lenght
print(f"In this list there are {len(fruits)} elements")
>>>
In this list there are 3 elements
So, the method len()
calculates how many elements are in a list, without worrying about their type. This means that the elements can be all numbers, all strings, or both of them: the len()
methods will count them all.
Sorting the elements of a list
Another action we may perform when we don't know a list is to sort its elements.
We have different methods to do so.
Let's start with the sort()
method:
# Creaye a list of numbers
numbers = [5, 2, 1, 4, 3]
# Sort the numbers
numbers.sort()
# Print sorted list
print(numbers)
>>>
[1, 2, 3, 4, 5]
So, we can just pass the list as the argument to the sort()
method and it will sort the elements.
But what if we want to sort a list containing strings? For example, suppose we want to sort the elements of a list in alphabetical order. We can do it like so:
# Create a list of strings
words = ['cat', 'apple', 'dog', 'banana']
# Sort in alphabeticla order
sorted_words = sorted(words, key=lambda x: x[0])
# Print sorted list
print(sorted_words)
>>>
['apple', 'banana', 'cat', 'dog']
So, in this case, we use the sorted()
method where we have to specify:
- The parameters regarding the list we want to sort. In this case,
words
. - The
key
. Which means we need to specify a methodology. In this case, we've used a lambda function that gets the first letter of each element withx[0]
by iterating through all the elements: this is the way we can select the first letter for each word.
Another way to sort strings is to sort them by the number of characters for each element. In other words, suppose we want to have the shorter words at the beginning and the longest at the end of our list. We can do it like so:
# Create a list of words
words = ['cat', 'apple', 'dog', 'banana']
# Sort words by lenght
words.sort(key=len)
# Print sorted list
print(words)
>>>
['cat', 'dog', 'apple', 'banana']
So, even with the sort()
method we can pass a parameter key
. In this case, we've chosen len
which counts the length of each word. So, the list is now ordered starting with the shortest words and ending with the longest ones.
List comprehension
List comprehension is a fast and concise way to create a new list using the power of loops and statements with one line of code.
Let's see an example. Suppose we want to take the numbers ranging from 1 to 6 and create a list with their squared values. We can do it like so:
# Create a list of squared numbers
squares = [x ** 2 for x in range(1, 6)]
# Print list
print(squares)
>>>
[1, 4, 9, 16, 25]
Now, we can reach the same result without using list comprehension but at the cost of a lot of code like so:
# Create empty list
squares = []
# Iterate over the numbers in the range
for squared in range(1, 6):
# Calculare squares and append to empty list
squares.append(squared ** 2)
# Print list
print(squares)
>>>
[1, 4, 9, 16, 25]
So, we get the same result but list comprehension makes us reach it with just one line of code.
We can also use if
statements in a list comprehension, making it way quicker and elegant than the "standard method", for which we'd need to iterate with a for
loop, and then select the values we need with an if
statement.
For example, suppose we want to create a new list of squared numbers, but we want only the ones that are even numbers. We can do it like so:
# Create a list with numbers in a range
numbers = list(range(1, 11))
# Get the even squared numbers and create a new list
squared_evens = [x ** 2 for x in numbers if x % 2 == 0]
# Print list with squared & even numbers
print(squared_evens)
>>>
[4, 16, 36, 64, 100]
So, here we need to remember that to take even numbers we can use the fact that they are divisible by two. So, x % 2 == 0
gets the numbers that, when divided by two, give a reminder of 0. Meaning: they're even numbers.
Conclusions
In this article, we've shown a comprehensive guide on Python lists.
Lists are a very important and useful data structure. They're not hard to learn, but are a fundamental asset for every Python programmer.
I'm Federico Trotta and I'm a freelance Technical Writer.
Want to collaborate with me? Contact me.