The aim of this tutorial is to show off Python’s data structures and the best way to use them. Depending on what you need from a data structure, whether it’s fast lookup, immutability, indexing, etc, you can choose the best d...
The aim of this tutorial is to show off Python’s data structures and the best way to use them. Depending on what you need from a data structure, whether it’s fast lookup, immutability, indexing, etc, you can choose the best data structure for the job and most of the time, you will be combining data structures together to obtain a logical and easy to understand data model.IntroductionPython data structures are very intuitive from a syntax point of view and they offer a large choice of operations. This tutorial tries to put together the most common and useful information about each data structure and offer a guide on when it is best to use one structure or another. You can choose different kinds of data structures depending on what the data involves, if it needs to be modified, or if it’s fixed data, and even what access type you would like, such as at the beginning/end/random etc.ListsA List represents the most versatile type of data structure in Python. It can contain items of different types and it has no rule against unicity. List indices start from zero, the elements can be sliced, concatenated, and so on. Lists also have a lot of similarities with strings, supporting the same kind of operations but unlike strings, lists are mutable.How to Construct a ListA list can be built using the keyword list or using square brackets: [], both of which accept comma separated values. Here’s an example:
>>> l = ['a', 'b', 123]
>>> l
['a', 'b', 123]
How to Retrieve an Element From a List
>>> l[0]
'a'
>>> l[10]
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range
As seen above, in order to access the data within your list, you must know what index position the element is at, otherwise you get an “index out of range” error.How to Slice a ListAll slicing operations return a shallow copy of the list. The slicing indexes are optional and they work in the same way as slicing indexes for strings.Here’s an example of how to slice a list:
>>> l = ['a', 'b', 123]
>>> l[:]
['a', 'b', 123]
>>> new_l = l[1:]
>>> new_l
['b', 123]
>>> l
['a', 'b', 123]
Let’s take a look at some other common list operations.Inserting and Removing Elements
>>> l = ['a', 'b', 123]
>>> l.append(234) #inserts an element at the end of the list
>>> l
['a', 'b', 123, 234]
>>> l.insert(2, 'c') #inserts an element into the third position
>>> l
['a', 'b', 'c', 123, 234]
>>> l.insert(-1, 111) #inserts an element into the second from last position of the list (negative indices start from the end of the list)
>>> l
['a', 'b', 'c', 123, 111, 234]
>>> l.remove(111) #removes an element based on value
>>> l
['a', 'b', 'c', 123, 234]
>>> l.remove('does not exist in the list')
Traceback (most recent call last):
File "", line 1, in
ValueError: list.remove(x): x not in list
Retrieving and Looking Up Elements Lists can also be used as stacks or queues because of how easy it is to add and remove elements from the beginning or end of the list.
>>> last_element = l.pop() #returns the last element, modifying the list
>>> last_element
234
>>> l
['a', 'b', 'c', 123]
>>> third_element = l.pop(2) #returns the third element, modifying the list
>>> third_element
'c'
>>> l
['a', 'b', 123]
>>> l.index('a')
0
>>> l.index('does not exist in the list')
Traceback (most recent call last):
File "", line 1, in
ValueError: 'does not exist in the list' is not in list
>>> l.count('a') #returns the number of occurrences of an element
1
Whole List Operations
>>> l.extend ([1, 2]) # concatenates a list on to the existing list
>>> l
['a', 'b', 123, 1, 2]
>>> l.sort()
>>> l
[1, 2, 123, 'a', 'b']
>>> l.reverse()
>>> l
['b', 'a', 123, 2, 1]
As you can see, it’s very easy to extend, sort, and reverse lists using the above methods.List ComprehensionsA list comprehension means, constructing a list in a way that is very natural from a mathematical point of vi