Data Structures in Python – Lists, Tuples, Sets, Dictionaries


1. Objective

In this python tutorial of data structures in python, we will talk about the data structures that python provides us with. These include lists, tuples, sets, and dictionaries. Let’s get started.

data structures in python

2. Introduction to Data Structures in Python

You can think of a data structure as a way of organizing and storing data such that we can access and modify it efficiently. Earlier, we have seen primitive data types like integers, floats, Booleans, and strings. Now, we’ll take a deeper look at the non-primitive data structures. Let’s begin with lists.

3. Lists in Python

A list in Python is a heterogeneous container for items. This would remind you of an array in C++, but since Python does not support arrays, it provides us with lists.

a. Declaring a List

To use a list, you must declare it first. Do this using square brackets, and separate values with commas.

>>> languages=['C++','Python','Scratch']

You can put any kind of a value in a list. This can be a string, a tuple, a Boolean, or even a list itself.

>>> list1=[1,[2,3],(4,5),False,'No']

Note that here, we put different kinds of values in the list. Hence, a list is (or can be) heterogeneous.

b. Accessing a List

1. Accessing an entire list

To access an entire list, all you need to do is to type its name in the shell.

>>> list1

[1, [2, 3], (4, 5), False, ‘No’]

2. Accessing a single item from the list

To get just one item from the list, you must use its index. However, remember that indexing begins at 0. Let’s first take a look at the two kinds of indexing.

  • Positive Indexing– As you can guess, positive indexing begins at 0 for the leftmost/first item, and then traverses right.
>>> list1[3]

False

  • Negative Indexing– Contrary to positive indexing, negative indexing begins at -1 for the rightmost/last item, and then traverses left. To get the same item form list1 by negative indexing, we use the index -2.
>>> type(list1[-2])

<class ‘bool’>

It is also worth noting that the index can’t be a float, it has to be an integer.

>>> list1[1.0]
Traceback (most recent call last):
File "<pyshell#219>", line 1, in <module>
list1[1.0]

TypeError: list indices must be integers or slices, not float

3. Slicing a List

Sometimes, you may not want an entire list or a single item, but a number of items from it. Here, the slicing operator [:] comes into play.

Suppose we want items second through fourth from list ‘list1’. We write the following code for this.

>>> list1[1:4]

[[2, 3], (4, 5), False]

Here, we wanted the items from [2,3] to False. The indices for these boundary items are 1 and 3 respectively. But if the ending index is n, then it prints items till index n-1. Hence, we gave it an ending index of 4 here.

We can use negative indexing in the slicing operator too. Let’s see how.

>>> list1[:-2]

[1, [2, 3], (4, 5)]

Here, -2 is the index for the tuple (4,5).

c. A list is mutable

Mutability is the ability to be mutated, to be changed. A list is mutable, so it is possible to reassign and delete individual items as well.

>>> languages

[‘C++’, ‘Python’, ‘Scratch’]

>>> languages[2]='Java'
>>> languages

[‘C++’, ‘Python’, ‘Java’]

Of how to delete an item, we will see in section d.

d. Deleting a List

Like anything else in Python, it is possible to delete a list.

To delete an entire list, use the del keyword with the name of the list.

>>> list1
Traceback (most recent call last):
File "<pyshell#225>", line 1, in <module>
list1

NameError: name ‘list1’ is not defined

But to delete a single item or a slice, you need its index/indices.

>>> del languages[2]
>>> languages

[‘C++’, ‘Python’]

Let’s delete a slice now.

>>> del languages[1:]
>>> languages

[‘C++’]

e. Reassigning a List

You can either reassign a single item, a slice, or an entire list. Let’s take a new list and then reassign on it.

>>> list1=[1,2,3,4,5,6,7,8]

1. Reassigning a single item

>>> list1[0]=0
>>> list1

[0, 2, 3, 4, 5, 6, 7, 8]

2. Reassigning a slice

Now let’s attempt reassigning a slice.

>>> list1[1:3]=[9,10,11]
>>> list1

[0, 9, 10, 11, 4, 5, 6, 7, 8]

3. Reassigning the entire list

Finally, let’s reassign the entire list.

>>> list1=[0,0,0]
>>> list1

[0, 0, 0]

To get an even deeper look into lists, read our article on Python Lists.

4. Tuples in Python

A tuple, like a list in Python, is a heterogeneous container for items. But the major difference between the two is that a list is mutable, but a tuple is immutable. This means that while you can reassign or delete an entire tuple, you cannot do the same to a single item or a slice.

To declare a tuple, we use parentheses.

>>> colors=('Red','Green','Blue')

a. Tuple Packing

Tuple packing is the term for packing a sequence of values into a tuple without using parentheses.

>>> mytuple=1,2,3,       #Or it could have been mytuple=1,2,3
>>> mytuple

(1, 2, 3)

b. Tuple Unpacking

The opposite of tuple packing, unpacking allots the values from a tuple into a sequence of variables.

>>> a,b,c=mytuple
>>> print(a,b,c)

1 2 3

c. Creating a tuple with a single item

Let’s do this once again. Create a tuple and assign a 1 to it.

>>> a=(1)

Now, let’s call the type() function on it.

>>> type(a)

<class ‘int’>

As you can see, this declared an integer, not a tuple.

To get around this, you need to append a comma to the end of the first item 1. This tells the interpreter that it’s a tuple.

>>> a=(1,)
>>> type(a)

<class ‘tuple’>

d. Accessing, Reassigning, and Deleting Items

We can perform these operations on a tuple just like we can on a list. The only differences that exist are because a tuple is immutable, so you can’t mess with a single item or a slice.

>>> del a[0]
Traceback (most recent call last):
File "<pyshell#251>", line 1, in <module>
del a[0]

TypeError: ‘tuple’ object doesn’t support item deletion

Even though this tuple has only one item, we couldn’t delete it because we used its index to delete.

For information about functions and methods on a tuple, refer to our article on Python Tuples.

5. Sets in Python

A set is a slightly different concept from a list or a tuple. A set, in Python, is just like the mathematical set. It does not hold duplicate values, and is unordered. However, it is not immutable unlike a tuple.

Let’s first declare a set. Use curly braces for the same.

>>> myset={3,1,2}
>>> myset

{1, 2, 3}

As you can see, it rearranged the elements in an ascending order.

Since a set is unordered, there is no way we can use indexing to access or delete its elements. Then, to perform operations on it, Python provides us with a list of functions and methods like discard(), pop(), clear(), remove(), add(), and more. Functions like len() and max() also apply on sets.

To get a very deep look into sets, read our tutorial on Python Sets.

6. Dictionaries in Python

Finally, we will take a look at dictionaries. Think of a real-life dictionary. What is it used for? It holds word-meaning pairs. Likewise, a Python dictionary holds key-value pairs. However, you may not use an unhashable item as a key.

To declare a dictionary, we use curly braces. But since it has key-value pairs instead of single values, this differentiates a dictionary from a set.

>>> mydict={1:2,2:4,3:6}
>>> mydict

{1: 2, 2: 4, 3: 6}

To access pairs from a dictionary, we use their keys as indices. For example, let’s try accessing the value 4.

>>> mydict[2]

4

To learn more about dictionaries, refer to our tutorial on Python Dictionaries.

7. Conclusion

Summing up for today, we learned about various user-defined data structures in python like lists, tuples, sets, and dictionaries. All of these have their own advantages and disadvantages. It is highly recommended to refer to our tutorials on each of those to sharpen your axes. See you later.

Learn the difference between Python lists vs Tuples.

Leave a comment

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