Lists are an essential component of many Python programs. Weather you are creating a list of people who are in an office room, or you are working on data for a machine learning program, you will eventually need to use and work with a list data structure to manage your data. Python provides a flexible and wide variety of built-in which enables us to do different operations on lists with ease.
I decided to write this tutorial in a different format from other tutorials on this site. In the next few sections, you will find information written in a “How-to” format. I hope this allows you, the reader to find the information that you are look for faster and to make things easier to understand.
Before we start, I recommend you to check out the book Python Crash Course: A Hands-On, Project-Based Introduction to Programming (click to check to Amazon). This was one of the few resources that I found very helpful to learn Python from scratch and to build a strong knowledge foundation in the programming language.
How to initialize a list in Python
In Python, lists are created by using the square brackets symbol [ ]. Lists are a collection of objects. These objects can be of any data type. For example, you can have a list of strings, a list of numbers, a list of lists of strings, a list of objects, etc..
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
numbers = [4, 8, 15, 16, 23, 42]
print(people)
print(numbers)
In the program above, we initialize two lists. The first one is for storing people’s names (yes, John is there twice) and the second is a list of numbers.
You can print lists in Python using the print function. The output of the program above will look as follows.
['John', 'Marie', 'Mark', 'John', 'Sarah']
[4, 8, 15, 16, 23, 42]
How to fetch items from a list
In Python, you can fetch different items from a list using their index (position) in the list. Like many programming languages, list indices in Python start from 0. This means, that the first item in the list will have an index 0, the second item will have an index 1, and so on.
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
firstPerson = people[0]
secondPerson = people[1]
print(firstPerson)
print(secondPerson)
Result:
['John', 'Marie', 'Mark', 'John', 'Sarah']
John
Marie
To fetch the last item in the list, you can use the index -1. The 2nd last item will have an index of -2, etc..
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
lastPerson = people[-1]
secondLastPerson = people[-2]
print(lastPerson)
print(secondLastPerson)
Result:
['John', 'Marie', 'Mark', 'John', 'Sarah']
Sarah
John
How to fetch a sub-list of items from a list
In Python, you can use indices not only to fetch single items from a list, but also multiple items that occupy a specific range of positions. This is done by defining a range of indices using the [x:y] notation.
For example, in order to get first two items in a list, you can specify the index [0:2]. This tells Python to get items from position 0 (inclusive) till position 2 (exclusive). This means that items in positions 0 and 1 will be fetched.
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
firstTwoPeople = people[0:2]
print(firstTwoPeople)
Result:
['John', 'Marie', 'Mark', 'John', 'Sarah']
['John', 'Marie']
You can also ask Python to fetch elements from the end of the list. For example, if you like to fetch the last two elements in the list, you can use the index range [-2:]. For example:
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
LastTwoPeople = people[-2:]
print(LastTwoPeople)
Result:
['John', 'Marie', 'Mark', 'John', 'Sarah']
['John', 'Sarah']
You can use the negative and positive values of the indexing range to obtain any range of elements in your list. For example, to get elements in positions 3 till 5, you can use the index [2:6].
How to get the number of items in a list
To count the number of elements in a list, you can use the len function in Python.
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
numOfpeople = len(people)
print(numOfpeople)
Result:
['John', 'Marie', 'Mark', 'John', 'Sarah']
5
How to add a new item to a list
You can add an item to a Python list by using the list append function. The append function will add the item to the end of the list. For example, let us add the name Sean to our people’s list.
people.append("Sean")
print(people)
Our list will now look as follows:
['John', 'Marie', 'Mark', 'John', 'Sarah', 'Sean']
Please note that the append function (as of Python 3.9) accepts only one item to be appended at a time. You can repeat the append operation if you have more than one item to add to your list (list.append(item1), list.append(item2))
How to add/append multiple items to a list at once
You can also add multiple items to a list at once. This can be done in two ways. Either by concatenating two lists using the + sign, or by using the list .extend function. Let us explore the concatenation option:
animals = ["dog", "cat", "bear", "mink"]
print(animals)
peopleAndAnimals = people + animals
print(peopleAndAnimals)
In our example, we created a new list called animals. We then created a new list, which the result of combining the list of people and list of animals. The result of our program will look as follows:
['dog', 'cat', 'bear', 'mink']
['John', 'Marie', 'Mark', 'John', 'Sarah', 'Sean', 'dog', 'cat', 'bear', 'mink']
Notice that you can repeat the concatenation operation for as many lists as desired.
peopleAndAnimals = people + animals + animals2
Another option is to use the .extend function.
animals.extend(["Mouse", "Eagle", "Fox"])
print("Animals after extension: ")
print(animals)
The following will be the result of the code snippit:
Animals after extension:
['dog', 'cat', 'bear', 'mink', 'Mouse', 'Eagle', 'Fox']
How to check if an item exists in a list
You can check if an item exists in a list by using the __contains__ function. The function will return the boolean value true if it does, and false if otherwise.
print(animals.__contains__("dog"))
Result:
True
How to remove an item from a list
There are different ways of deleting items from lists. The way that you choose to do so will depend on the outcome that you desire since each way has a different side effect on your list and your data.
Using the pop() function
The pop function allows you to remove an item from the list. The pop function will return as a result the item that was “popped” from the list. By default, the pop function will remove the last item from the list.
print(animals)
lastAnimal = animals.pop()
print(animals)
print(lastAnimal)
The program above will remove the last element in the list.
['dog', 'cat', 'bear', 'mink', 'Mouse', 'Eagle', 'Fox']
['dog', 'cat', 'bear', 'mink', 'Mouse', 'Eagle']
Fox
You can also instruct the program to pop an item at a specific position. For example, we can pop the first item by passing on the index 0 to the function.
print(animals)
lastAnimal = animals.pop(0)
print(animals)
print(lastAnimal)
Result:
['dog', 'cat', 'bear', 'mink', 'Mouse', 'Eagle', 'Fox']
['cat', 'bear', 'mink', 'Mouse', 'Eagle', 'Fox']
dog
Using the remove() function
Another way of removing items from lists is to use the remove function. The remove function is used to remove the first occurrence of a specific item from the list. Unlike the pop function which works with indices, the remove function takes in the item to be removed as an argument.
Another important difference between remove and pop is that remove will not return the item removed as a result of the operation. Let us try out the remove function.
print(animals)
animals.remove("cat") ##no output here
print(animals)
Result:
['dog', 'cat', 'bear', 'mink', 'Mouse', 'Eagle', 'Fox']
['dog', 'bear', 'mink', 'Mouse', 'Eagle', 'Fox']
Again, keep in mind that the remove function will remove only the first occurrence of an item. For example:
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
people.remove("John")
print(people)
result:
['John', 'Marie', 'Mark', 'John', 'Sarah']
['Marie', 'Mark', 'John', 'Sarah']
Notice that only the first “John” was removed, but not the second one.
Using del
Finally, we can remove an item from a list using the delete keyword del.
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
del people[1]
print(people)
In the example above, we delete the item at index position 1 (“Marie”).
['John', 'Marie', 'Mark', 'John', 'Sarah']
['John', 'Mark', 'John', 'Sarah']
Like the pop function, del also requires the index of the item that needs to be removed from the list. However, unlike pop, the item reference is not returned and is deleted from memory.
You can also use the del keyword to delete multiple items from a list. For example, if we would like to delete the first two items from the list, we could do it as follows:
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
del people[0:2]
print(people)
result:
['John', 'Marie', 'Mark', 'John', 'Sarah']
['Mark', 'John', 'Sarah']
How to convert a list into a string
Sometimes you need to convert a list into a String. For example, when you would like to print the contents of a list inside a print statement which contains other strings, or when you need a string representation of your list which will be sent to a different system.
This can be easily done using the str() function.
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print("The people in the list are : " + str(people))
If you omit the str function above, then Python will give you an error. This is because Python cannot tell if you require the string representation of the list or if you are attempting to concatenate a list to a string.
print("The people in the list are : " + people)
TypeError: can only concatenate str (not "list") to str
How to convert a list into a set in Python
If you would like to remove duplicate values in a Python list, then you can simply convert your list into a set using the set function. A set is a list of non-repeating items. This means that items that are found in a set will not be found again later in the set.
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
peopleSet = set(people)
print(peopleSet)
The first print statement will provide us the list of names, however, the second print statement will provide us with the unique set of names.
['John', 'Marie', 'Mark', 'John', 'Sarah']
{'Sarah', 'Mark', 'Marie', 'John'}
Please keep in mind that the set function will not preserve the order of your list. Depending on your need, you might need to process the result of the set function to get back your previous order.
How to check if a list is empty
In Python, if you pass a list as an argument to an if statement, it will be evaluated to “true” if your list contains elements, and false otherwise. For example:
myList = []
if myList:
print("List is not empty")
else:
print("list is empty")
Since myList is does not contain any elements, the flow of the program will go to the else statement.
list is empty
You can also compare your list to an empty list by using the == and != signs.
if myList!=[]:
How to loop through a list
You can loop through sets in different ways, but the most popular and readable way in Python to achieve this is by using for loops.
people = ['John', 'Marie', 'Mark', 'John', "Sarah"]
print(people)
for person in people:
print(person +" is in the list")
result:
['John', 'Marie', 'Mark', 'John', 'Sarah']
John is in the list
Marie is in the list
Mark is in the list
John is in the list
Sarah is in the list
When creating a for loop for collections, you first define a reference for single items that are going to be operated upon in your list. In our example, this reference is person. You can then use this reference in your loop to perform operations on each of your items in the list.
We will explore loops in more detail in a later tutorial.
Summary
In this post, we discussed how to perform some of the most popular and needed operations on lists.
Do you think there is something that we missed? or something that deserves its own article? Then please write us an email and we will do our best 🙂
Thanks for reading and hope to see you again.