Lists in Python

One of the essential features of any programming language is the ability to store collection of data into a single variable. In Python there are 4 data types that allow to store collections of data and in this section we will focus on Lists while the section below will describe the Tuples. A list is created by using square brackets or the constructor list() (this is also used to convert another data type to a list). It can be initialized empty or with already some values as shown in the example below.

l1=[] #Create empty list
l2=list() #Create empty list
l3=[1,5,7] # Create a list with 3 elements
print(l3)
l4=list((1,2)) # Create a list with 2 elements
print(l4)

A list has several properties:

  • It is ordered, this means that the items within the list have a specific index which defines the order.
  • The list can be changed, so it is possible to modify its items and include/remove the contained items.
  • It is possible to create duplicates given that the index is the way used to distinguish between items in the list (two items with same value will still have different indexes).
  • It can contain a mix of data types, so some elements can be strings other can be numeric such as float or integer and so on. For example l1=[1,4.2,"hello"].
Similarly to strings, which is seen by Python as a collection of characters, it is possible to know the number of elements within a list by using the function len() as shown below

l1=[1,2,3,4,5]
print(len(l1)) #It prints 5
Operations on Lists

To see the value of a specific item within the list it is required to use the index which starts with 0. The index value can also be negative and in this way Python begins from the end of the list.

l1=[4,25,10,5]
print(l1[0])  # Prints 4
print(l1[2])  # Prints 10
print(l1[-1]) # Prints 5 (it begins from the end)

It is also possible to see a subset of the list (i.e. more than one item) by using the comma between each index or by using the colon between to indexes (item of index before colon is included but last is not). If the index before the colon is not included Python assumes that it begins from the beginning, similarly if the index after the colon is not included then Python assumes that it continues until the end.

l1=["computer","smartphone","tablet","robot","laptop"]
print(l1[1:3]) # Prints smartphone and tablet
print(l1[:2])  # Prints computer and smartphone
print(l1[3:])  # Prints robot and laptop

To change one or more than one items within a list, it is required to provide the indexes of the items that need to be replaced and the values of the new items as shown in the example below.

l1=[2.1,5,8.4,7,20]
l1[0]=4 # First element becomes 4
l1[2:5]=[10,11,14.5] # Last three elements are changed
print(l1) # Now l1 is [4,5,10,11,14.5] 

To merge two or more lists together it is possible to sum them together by simply using the plus operator.

l1=[1,2,3]
l2=[4,5,6]
l3=[7,8,9]
l4=l1+l2
l5=l1+l2+l3
print(l4)   # Prints [1,2,3,4,5,6]
print(l5)   # Prints [1,2,3,4,5,6,7,8,9]

To repeat the values of a list $n$ times just multiply the list by $n$.

l1=[10,20,40]
n=3
print(l1*n)  # Prints [10,20,40,10,20,40,10,20,40]
Functions for Lists

There are several built-in functions (available by simply adding a dot to the variable name, so list_name.function()) that are associated to a List and they can be useful for different types of operations. Here we mention some of the most relevant. To insert a new item use the function insert() and provide 2 inputs: the index (i.e. where it needs to be located in the list) and the value of the item.

l1=[5,10,23]
l1.insert(1,8)    # Insert 8 in second position
print(l1)         # Prints [5,8,10,23]
l1.insert(3,"Hi") # Insert "Hi" in 4th position
print(l1)         # Prints [5,8,10,"Hi",23] 

To add a new item at the end of the list there is the function append() and the only input is the value of the item.

l1=[5,10,23]
l1.append(48)   # Append 48 at the end
print(l1)       # Prints [5,10,23,48]

To remove an item from the list there are two ways: if the value of the item is known then the function is remove() while if the index of the item is known the function is pop().

l1=[1.5,3.2,4.8,7.9]
l1.remove(7.9) # Removes the element 7.9
l1.pop(1)      # Removes the second element 3.2
print(l1)      # Prints [1.5,4.8]

A very important function is copy(). This is used to copy the values of a list to another list. In Python with a1=a2, where they are both variables, the value of $a2$ is copied into $a1$ and now any modification to $a1$ will not affect $a2$ and viceversa. This is however not true for lists, in case of l1=l2 the list $l1$ is a reference of $l2$ so they are essentially linked together but have different names: a modification to $l1$ will affect $l2$ and viceversa. To have a completely separate list which is a copy of another list then the function mentioned above is used.

l1=[1,2,3]
l2=l1
l3=l1.copy()
l2[0]=5   #Change first element in l2
print(l1) #This also changes l1 which now is [5,2,3]
print(l3) #Prints l3 which is not affected and still [1,2,3]
l3[0]=10
print(l3) #Now l3 is [10,2,3]
print(l1) #This does not change l1
print(l2) #This also does not change l2

To sort alphanumerically a list the function is sort() and by using the setting reverse=True it is possibleto sort it in descending order.

#Example 1
l1=[4,1,8,7.2,3.8]
l1.sort()    # This sorts l1
print(l1)    # Now l1 is [1, 3.8, 4, 7.2, 8]
#Example 2
l2=['sort','name','algorithm','python','list']
l2.sort()   # Now l2 is sorted alphabetically
print(l2)   # This is ['algorithm', 'list', 'name', 'python', 'sort']
l2.sort(reverse=True) # This reverses the order
print(l2)   # Now the list is ['sort', 'python', 'name', 'list', 'algorithm']

Finally to remove all elements of a list there is the function clear() while to completely delete a list (or any variable in Python) there is the keyword del.

l1=[1,10,100]
print(l1)     # Prints [1,10,100]
l1.clear()    # It clears the list
print(l1)     # Prints []

l2=['a','b','c']
del l2        # Cancels the list, it does not exist anymore
		      # If try to use l2 Python throws an error "NameError: name 'l2' is not defined"

Try these operations and functions in the console below to gain familiarity with lists.


Tuples in Python

The Tuples are another of the 4 data types that allow the storage of collections of data. To create a Tuple it is required to use the round brackets instead of the square brackets and it is possible to convert a collection of data into a tuple by using the constructor tuple(). To check the data type the function is type().

t1=() #Empty Tuple
t2=(1,2.4,'hello') # Tuple initialized with some elements
print(t2)
t3=tuple([1,5,2])  # Convert List to Tuple
print(type(t3))    # The type is 'tuple'

A tuple has slightly different properties if compared to lists:

  • It is ordered like a list, this means that the items within the tuple have a specific index which defines the order.
  • However it cannot be changed, it is not possible to modify its items and include/remove the contained items.
  • It is possible to create duplicates given that the index is the way used to distinguish between items in the tuple (two items with same value will still have different indexes).
  • It can contain a mix of data types, so some elements can be strings other can be numeric such as float or integer and so on. For example t1=(2,5.1,"hi").
The reason for the existence of tuples is to store values that do not need to be changed or values that need to be protected, also their immutable structure make them faster than lists for the operations. Similarly to lists, it is possible to know the number of elements within a tuple by using the function len() as shown below.

t1=(2,5,23,40)
print(len(t1)) #It prints 4
Operations on Tuples

Given that Tuples cannot be changed, the only operations that can be done is their creation and accessing the data within the tuple. To access a value of a specific item within the tuple, similarly to lists, it is required to use the index which starts with 0. All the considerations on lists work with tuples as well.

t1=(1,"tuple",2.5,20)
print(t1[0])   # Prints 1
print(t1[1])   # Prints "tuple"
print(t1[-1])  # Prints 20 (it begins from the end)
print(t1[1:3]) # Prints ('tuple', 2.5)
print(t1[2:]) # Prints (2.5, 20)

Given that tuples cannot be changed, they need to be converted for example to lists in order to be able to change one or more than one items and then converted back to tuples: in this way it is possible to perform/use any allowed list operation/function and then convert it back to a tuple which cannot be modified.

t1=(1,20,5,10)
l1=list(t1)    # Convert tuple to list
l1[0]=2        # First element changes from 1 to 2
l1.append(8)   # Element with value 8 added to the list
l1.sort()      # Sorts the list
t1=tuple(l1)   # Convert the list to tuple
print(t1)      # Prints (2, 5, 8, 10, 20)

Similarly to lists, to merge two or more tuples together it is possible to sum them together by simply using the plus operator and to repeat the values of a tuple $n$ times just multiply the tuple by $n$.

t1=(1,2)
t2=(3,4)
t3=t1+t2      # Merges t1 and t2
print(t3)     # Prints (1,2,3,4)
t4=t3*2       # Repeat the tuple 2 times
print(t4)     # Prints (1,2,3,4,1,2,3,4)
t5=t1+t2+t3   # Merges t1 and t2 and t3
print(t5)     # Prints again (1,2,3,4,1,2,3,4)
Functions for Lists

Tuples only have 2 built-in functions which are count() and index(): the first is used to count the number of occurrences of a specific value while the second outputs the index in the tuple of a specific value. Also, del deletes a tuple. Some examples are shown below.

t1=(20,14,2,1,2,5,2,48,2)
print(t1.count(2))         # Prints 4
print(t1.index(1))         # Prints 3 given that t1[3]=1
print(t1.index(2))         # Prints 2 because it stops at first match
print(t1.index(2,5))       # Prints 6 because it begins the search from index=5
del t1                     # Cancels the tuple, it does not exist anymore

Try these operations and functions in the console below to gain familiarity with tuples.