Python list – A complete overview

Table of Contents

Introduction

Python list is a special data type used to store data and it is one of the 4 built-in Python data types.
The other 3 are Dictionary, Tuple and Set but they will be explained different posts.

This post will explain to you the following topics:

  • List creation
  • Access to list elements
  • List slicing
  • Change list element
  • Delete list element
  • Python list methods
  • List comprehension

Create Python list

To create a Python list you can use the following command:

my_list = [1, 2, 3, 4, 5]

This code creates a list named my_list with 5 elements that are inside square brackets [].

Please note that it is possible to have a list with elements of different data types:

my_list = ["a string", 1, 2.9]

With duplicates

my_list = ["a string", 1, 2.9, "a string"]

And also lists of lists:

my_list = [["a string", "another string"], [1,2,3,4]]

In this example we have a list composed by two lists.

Access to python list elements

It is possible to access to the list elements using indices.
It is important to remember that the indices associated with the elements of a list start from zero!

indices in list
How indices are computed

Check the snippet below to better understand how it works!

a_list = ["my", "handsome", "element"]
# get first element of the list
first_element = a_list[0]
print(first_element)   #  "my"
# get third element of the list
third_element = a_list[2]
print(third_element)   #  "element"

Easy right?! But what about if do we have nested lists?

The logic is the same, we need to use indices to get elements. Check this example:

my_list = [["a string", "another string"], [1,2,3,4]]
# get first element of my_list
first_element = my_list[0]
print(first_element , type(first_element)   # ["a string", "another string"], <type 'list'>
# get first element of nested list
first_element_2 = my_list[0][0]
print(first_element2 , type(first_element2)   # "a string, <type 'str'>

List slicing

Another important concept for accessing the elements of the list is the slicing,
It allows you to access a range of items at once using the : operator.

my_list = ["a", "b", "c", "d", "e", "f", "g"]
# get elements from index 3 to 5
print(my_list[3:6])  # ['d', 'e', 'f']
# get elements from index 3 to the end
print(my_list[3:])  # ['d', 'e', 'f']
# get eleents from the beginning to index 4
print(my_list[:4])  # ['a', 'b', 'c', 'd']
# get the entire list
print(my_list[:])  # ['a', 'b', 'c', 'd', 'e', 'f', 'g']

It is important to remember that the second index is not in the selected slice

A peculiarity of slicing is that you can also use the step value like the example below.

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# get elements from index 1 to index 5 using 2 steps
print(my_list[1:6:2])  # ['b', 'd', 'f']

Last but not least, it is also possible to use negative indices but you must remember that you go backwards.

my_list = ["a", "b", "c", "d", "e", "f", "g"]
# get elements from the beginning to index 3 using negative index
print(my_list[:-3])  # ['a', 'b', 'c', 'd']

Change python list element

It is possible to change an element of a list using indices.
Let’s see this simple example to understand better how it works:

a_list = ["my", "handsome", "element"]
# change first element of the list
a_list[0] = "your"
print(a_list)   # ["your", "handsome", "element"]

As you can see, to change an element of a list is very simple, just take the element and change it!

Delete list element

It is possible to delete a list element using Python del statement.

my_list = [1,2,3,4]
# delete second element (index 1)
del my_list[1]
print(my_list)  # [1,3,4]

It is also possible to delete more than one element at the time and this is done using list slicing.

my_list = [1,2,3,4]
# delete second and third elements (index 1 and 2) 
del my_list[1:3]
print(my_list)  # [1,4]

Did you notice? we decide to remove index 1 and 2 but in del statement we used 1 and 3.
This because the index representing the end is exclusive, basically you always have to think about one more element at the end.

Using del you can also delete the entire list but remember, if the list does not exist a NameError exception is raised.

del my_new_list  # NameError
my_list = [1,2,3,4]
del my_list

This is only one way to remove elements from a list indeed, in the next sections you will see how to use remove and pop method.

Python list methods

In this section, the Python list methods are explained with examples (Official documentation link).

list.append(x)

This method is used to add a new element at the end of the list.

my_list = [1,2,3,4]
my_list.append(5)
print(my_list)  # [1,2,3,4,5]

list.extend(iterable)

It extends the list using another list (or iterable).

my_list = [1,2,3,4]
my_list.extend([5,6,7])
print(my_list)  # [1,2,3,4,5,6,7]

list.insert(i, x)

Insert a new element at a given position where parameter i represents the index of the new element and x the item.

my_list = [1,2,3,4]
my_list.insert(2, 10)
print(my_list)  # [1, 2, 10, 3, 4]

list.remove(x)

It removes the element from the list and raise ValueError if there is no such element.

my_list = [1,2,3,4]
my_list.remove(2)
print(my_list) # [1, 3, 4]
my_list.remove(10)  # ValueError

BE CAREFUL!
Duplicates are not removed but only the first occurrence is deleted.

my_list = [1,2,3,4,3,3]
my_list.remove(3)
print(my_list) # [1, 2, 4, 3, 3]

list.pop([i])

This method removes the element at the i index of the list. If no parameter is specified, it removes the last element of the list.
The important thing to remember is that pop returns the removed element.

my_list = [1,2,3,4]
removed_elem = my_list.pop(2)
print(removed_elem) # 3
my_list = [1,2,3,4]
removed_elem = my_list.pop()
print(removed_elem) # 4

list.clear()

This method removes all elements from the list.

my_list = [1,2,3,4]
my_list.clear()
print(my_list)  # []

list.index(x[, start[, end]])

This method returns the index in which the first element x of the list is found.
It is possible to limit the search using start and end to slice the list.

my_list = [1,2,3,4,2]
idx = my_list.index(2)
print(idx)  # 1

list.count(x)

Return the number of times x appears in the list.

my_list = [1,4,3,4]
num = my_list.count(4)
print(num)  # 2

list.sort(*, key=None, reverse=False)

Very simple method to sort the elements of the list. It is possible also to sort in reverse order using the parameter.

my_list = [5,6,7,2,9,10]
my_list.sort()
print(my_list)  # [2, 5, 6, 7, 9, 10]

list.reverse()

Reverse the elements of the list in place.

my_list = [1,2,3,4]
my_list.reverse()
print(my_list)  # [4, 3, 2, 1]

list.copy()

This method returns a shallow copy of the list.

my_list = [1,2,3,4]
my_list_copied = my_list.copy()
print(my_list)  # [1, 2, 3, 4]
print(my_list_copied)  # [1, 2, 3, 4]

Count the number of items in a list

This is not a list method but it will be useful for sure!

my_list = [1,2,3,4]
my_list_len = len(my_list)
print(my_list_len)  # 4

The len(list) function will return the number of elements in the list.

Check if element is in a list

A simple way to check if a list contains an element is to use the in Python operator.

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
"d" in my_list  # True
"z" in my_list  # False

List comprehension

List comprehension is a way to create and insert elements into a list starting from another list in only one line!

Suppose you have a list of numbers from 1 to 10 and you want to create a new list where each ad element is added 5.
How to do it using a for loop?

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_list = []
for element in my_list:
    new_list.append(element*5)
print(new_list)  #  [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

The code above can be refactored using list comprehension:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_list = [element*5 for element in my_list]
print(new_list)  #  [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

As you can see the number of lines of code has been reduced to 1.
The general list comprehension syntax is the following:

new_list = [expression for item in iterable]

List comprehension topic is very broad and in this post we have made only a hint.
I will write a post dedicated to this very interesting topic.

Conclusion

This post explain you how to handle basic python list operations.
Now you have learned how to create new lists and manage all its methods.
Let me know in the comments if it was useful to you or if you are in trouble!

If this topic is clear to you, take a look at the latest posts!

Leave a Comment

Your email address will not be published. Required fields are marked *