Skip to content

Python Lists, with Examples

Lists in Python are a data structure that stores an ordered collection of items, which don't have to be of the same type. Learn how to use them with examples.

You can download the project for this post by clicking HERE.

Lists (or ‘List’) in Python are a very flexible type of data structure that stores an ordered collection of items that don’t have to be of the same type. In other programming languages a list would be equivalent to an array, although Python doesn’t require the elements of the list to be of the same type (‘int’, ‘float’, ‘chr’, ‘str’, ‘bool’, ‘object’).

Let’s look at an example of a list in Python:

# We declare a list with different data types
lista = [1, 3.1416, 'j', 'jarroba.com',  True]

As you can see, we declare the list between the characters '[ ]' and the elements in this list are of different types. Next, let’s loop over the list (with a foreach) and print its elements along with the data type of each one:

print 'Imprimimos los elementos de una lista y el tipo de dato de cada elemento'
for l in lista:
    print '%s - %s' %(l, type(l))

The result of this code is the following:


Imprimimos los elementos de una lista, con su tipo de dato y el contenido
1 - <type 'int'>
3.1416 - <type 'float'>
j - <type 'str'>
jarroba.com - <type 'str'>
True - <type 'bool'>

As we’ve just shown, lists in Python let you work with elements of different data types.

Now let’s go through the methods (or functions) for working with lists in Python, and then look at examples of how these methods work:

# Declaring a list
lista = list()

# Counts the number of elements in the list
len(lista)

# Adds an element (x) to the end of the list.
lista.append(x)

# Inserts an element (x) at a given position (pos)
lista.insert(pos, x)

# Joins two lists (appends lista2 (the one passed as a parameter) to lista)
lista.extend(lista2)

# Removes the first element of the list whose value is x. If it doesn't exist, it raises an error
lista.remove(x)

# Removes the element at the given position in the list, and returns it.
lista.pop(pos)

# Removes all the elements from the list (lista.clear())
del lista[:]

# Returns the index in the list of the first element whose value is x.
lista.index(x)

# Returns the number of times x appears in the list.
lista.count(x)

# Sorts the items of the list
lista.sort(cmp=None, key=None, reverse=False)

# Reverses the elements of the list.
lista.reverse()

# Returns a copy of the list (lista.copy())
listaCopia = lista[:]

Now that we’ve seen the methods (or functions) that let us work with lists, let’s see how to use them. To do that, we’ll create a list where we’ll store the positions that football players can play in a football match; that is, we’ll store string elements.

First, we create a list variable (we define this variable explicitly) that we’ll call 'demarcaciones' and we’ll add the elements with the "append(x)" method:

# Example of a list where we'll store the positions in football
demarcaciones = list()

# We insert some positions
demarcaciones.append('Defensa')
demarcaciones.append('Lateral')
demarcaciones.append('MedioCentro')
demarcaciones.append('Centro Campista')
demarcaciones.append('Extremo')
print demarcaciones

If we run this piece of code, in which we insert elements into the list and print it, we get the following:


['Defensa', 'Lateral', 'MedioCentro', 'Centro Campista', 'Extremo']

Once we have elements in our list, we can count them like this:

# We check how many elements our list has
numElem = len(demarcaciones)
print 'Número de elementos en la lista: %d' %numElem

The output is the following:


Número de elementos en la lista: 5

The "len()" function isn’t specific to counting the number of elements in a list; it also works for counting the number of characters in a string, the number of elements in a dictionary, etc. We show it in this tutorial so you know that the number of elements in a list is counted with this function.

Let’s try the "insert(pos,x)" method, which inserts an element 'x' at the position 'pos' of the list that we specify. Let’s see an example:

# We insert elements at specific positions
demarcaciones.insert(0, 'Portero')
demarcaciones.insert(6, 'Delantero')
print demarcaciones

As you can see, we insert the elements 'Portero' and 'Delantero' at positions 0 and 6 of the list, respectively. REMEMBER: lists (as in other programming languages) start numbering at position '0'. If we run the previous piece of code, we’ll see that we do indeed insert 'Portero' and 'Delantero' at the first and last positions.


['Portero', 'Defensa', 'Lateral', 'MedioCentro', 'Centro Campista', 'Extremo', 'Delantero']

The next method, "extend(list)", joins the elements of the list passed as a parameter to the list. In the following piece of code we create a list (called 'lista2') that we’ll join, or concatenate, to the demarcaciones list like this:

# We concatenate two lists
lista2 = ['Arquero', 'Carrilero', 'Portero', 'Lateral']
demarcaciones.extend(lista2)
print demarcaciones

The result of joining these two lists is the following (demarcaciones + lista2):


['Portero', 'Defensa', 'Lateral', 'MedioCentro', 'Centro Campista', 'Extremo', 'Delantero', 'Arquero', 'Carrilero', 'Portero', 'Lateral']

The next method we’re going to try is "remove(x)", which removes the first element 'x' found in the list. In the example below we’ll remove the first element that is 'Lateral':

# We remove the first occurrence of the element 'Lateral' from the list
demarcaciones.remove('Lateral')
print demarcaciones

The result is the following content. As you can see, it removed the first occurrence of 'Lateral' (which was in third place), but it didn’t remove the second occurrence of 'Lateral', which is in the last position:


['Portero', 'Defensa', 'MedioCentro', 'Centro Campista', 'Extremo', 'Delantero', 'Arquero', 'Carrilero', 'Portero', 'Lateral']

Another removal method is "pop(pos)", which removes the element at the position 'pos' passed as a parameter. As you can see in the following example, we’ll remove the element in the third position (the 'MedioCentro' element). Since lists start numbering at '0', to remove the third element we have to pass a '2' as the parameter:

# We remove the third element of the list. PS: lists start at element 0
demarcaciones.pop(2)
print demarcaciones

The result is that it removed the third position; that is, it deleted 'MedioCentro'


['Portero', 'Defensa', 'Centro Campista', 'Extremo', 'Delantero', 'Arquero', 'Carrilero', 'Portero', 'Lateral']

The next method we’ll look at is "index(x)", which returns the position of the first element 'x' in the list. If we search for the value 'Extremo' in the list, it returns '3' (which corresponds to the fourth position):

# We look for the position of the first element with value = 'Extremo'
print demarcaciones.index('Extremo')

The "count(x)" method returns the number of times the element 'x' appears in the list. Below is an example in which we count the number of times the elements 'Portero' and 'Delantero' appear, respectively:

# We check the number of times the elements 'Portero' and 'Delantero' appear in the list
print demarcaciones.count('Portero')
print demarcaciones.count('Delantero')

The result is that the element 'Portero' appears 2 times and the element 'Delantero' appears only once:


2
1

To reverse the list we have the "reverse()" method. Let’s see an example of how we would reverse the list:

# We reverse the elements of the list
demarcaciones.reverse()
print demarcaciones

The result is the reversed list:


['Lateral', 'Portero', 'Carrilero', 'Arquero', 'Delantero', 'Extremo', 'Centro Campista', 'Defensa', 'Portero']

To make a copy of a list, you can use the "copy" method, although for that we would first have to do an "import copy". To make things much simpler and to avoid importing any extra library, we’ll make copies of a list like this:

# We make a copy of the demarcaciones list
copiaDemarcaciones = demarcaciones[:]
print 'Copia %s' %copiaDemarcaciones

What we’re doing is copying the contents of the whole 'demarcaciones' list ( [ : ] ) into the variable 'copiaDemarcaciones'. In this case, unlike other languages such as Java, we’re not creating a reference to a list, but making a copy of the list; that is, if we manipulate the 'copiaDemarcaciones' list (delete, insert, reverse, …) it won’t affect the 'demarcaciones' list, since they are copies in memory and not references. The result of the previous piece of code (the copy) is the following:


Copia ['Lateral', 'Portero', 'Carrilero', 'Arquero', 'Delantero', 'Extremo', 'Centro Campista', 'Defensa', 'Portero']

To remove all the elements of a list you can use the "remove()" method, although it’s better to clear the list like this:

# We remove all the elements of the 'copiaDemarcaciones' list
del copiaDemarcaciones[:]
print copiaDemarcaciones

In this case we’re going to clear the contents of the 'copiaDemarcaciones' list, and we can see that the result is a list with no elements:


[]

Finally, let’s look at one of the most interesting list methods, the sorting method "sort()". Abstracting away the algorithm it uses to sort the list (quicksort, direct insertion, bubble sort, etc.), the "sort()" method lets you sort the list in order (alphabetical, numerical, etc.) in either direction.

Let’s look at an example and sort the list alphabetically. To do that, we do the following:

# We sort the demarcaciones list in alphabetical order
demarcaciones.sort()
print demarcaciones

The result is the list sorted in alphabetical order:


['Arquero', 'Carrilero', 'Centro Campista', 'Defensa', 'Delantero', 'Extremo', 'Lateral', 'Portero', 'Portero']

The "sort()" method accepts a series of parameters for sorting, since if the list contained objects instead of atomic values, it could sort them by some attribute of the object. In this tutorial we won’t go into that detail and we’ll only see how to sort the list in reverse order by passing the parameter 'reverse = True|False'. Let’s see the example:

demarcaciones.sort(reverse=True)
print demarcaciones

As you can see, the result is the list sorted in alphabetical order, but in reverse: 


['Portero', 'Portero', 'Lateral', 'Extremo', 'Delantero', 'Defensa', 'Centro Campista', 'Carrilero', 'Arquero']

Let’s look at another list sorting example, but this time with numbers instead of words. In the following piece of code we’ll see how the 'listaNumero' list would be sorted in both ascending and descending order:

print '\n\n*******    Ordenación de listas    ******'
listaNumero = [5,2,9,1,12,6,8,3,4]

print 'Lista Desordenada'
print listaNumero

print 'Lista ordenada de forma ascendente (Aqui da igual pasarle "reverse=False" como parámetro)'
listaNumero.sort(reverse=False)
print listaNumero

print 'Lista ordenada de forma descendente'
listaNumero.sort(reverse=True)
print listaNumero

The result is the following:


*******    Ordenación de listas    ******
Lista Desordenada
[5, 2, 9, 1, 12, 6, 8, 3, 4]
Lista ordenada de forma ascendente (Aqui da igual pasarle "reverse=False" como parámetro)
[1, 2, 3, 4, 5, 6, 8, 9, 12]
Lista ordenada de forma descendente
[12, 9, 8, 6, 5, 4, 3, 2, 1]

To learn more about sorting lists in Python, see the following tutorial: "Ordenar listas en Python, con ejemplos"

“Python Lists, with Examples” by Ricardo Moya at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

Ricardo Moya

I work in Machine Learning and Big Data. I like learning new technologies and explaining them as clearly as I can on this site.

You may also like

Sorting Lists in Python, with Examples

Learn the different ways to sort a list in Python, specifying the field, substring, attribute, etc. to sort by, with clear and practical examples.

Aug 30, 2015

Python Dictionary, with Examples

Learn how Python dictionaries work: declaring them, looping over key-value pairs and using methods like get, pop, update and more, with practical examples.

May 5, 2015

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.