Python tuples

by Alex
Python tuple

In order to improve the program code, to add new important functions to it, various methods are used. These include: creating lists, tuples or dictionaries. In this article we will consider when they are used, how they differ, how to create and how to work with tuples in Python 3.

What is a tuple

A tuple is an immutable structure of predefined values. It is very similar to a list, but the latter is subject to change. So, if you need to fix an element in a list, you can do so by directly specifying:

b = [4, 6, 8]
[4, 6, 8]
b[1] = 13
[4, 13, 8]

If you write a similar code but try to apply it to a tuple, it won’t work and an error message will be displayed. This is said to be important because the data cannot be changed in this way, either accidentally or intentionally. Also, in python it is not possible to add an item to a tuple. It is possible, however, to bring it into a list, add an item. After that the resulting list can be converted back. Another advantage of a tuple is that it has a smaller size, which is checked by using the sizeof command. This shows how much the object occupies in bytes:

a = (2, 4, 6, 8, 10, 12)
b = [2, 4, 6, 8, 10, 12]

From this code, you can see that the tuple (in parentheses) takes 36 bytes and the list (in square brackets) takes 44 bytes.


A tuple is defined exactly like a list, but the enumeration is in parentheses, not square brackets. The elements will stand in a certain order, and their numbering always starts with zero. For a non-empty tuple the first element will be zero. A negative index will allow counting everything from the end (from the right side). Here is an example of creating a normal tuple in Python:

a = (1,2,3)

You can convert a list to a tuple as follows:

a = tuple([1,2,3])

Consider a tuple with a negative index:

n = ("a", "b", "c", "d", "e")


That is, the screen displays the first element not from the beginning but from the end. To create a tuple with one element, you need to write the following:

a =(3,)


Note that even if there is only one element, it must still be followed by a comma. Sometimes generators are used to create tuples. Usually, they are used to compactly and conveniently create a necessary collection of elements. Here is an example:

a = tuple(i for i in range(0, 10))

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Above is the tuple generator. That is, we created a generator. We then converted it to a tuple using the tuple keyword.

Remember that you can not apply slices to the generator. If necessary, you can lead the generator to tuple and only then make the cut.

More information about slices is described below in section “Applying to element”. Using the tuple generators is similar to the generators of the list.

Referencing an element

Each element has its own index. That is, in Python, to address a tuple element, you simply need to specify its index. Recall that counting starts with zero. Let’s look at the code:

b = (4, 6, 8)


It is possible to extract both an element and a slice from a tuple. In this case we will get a tuple consisting of elements in the gap of the slice. It should be clarified that when specifying a slice, the numbers of the spaces between the elements are used, not the numbers of the elements. Before the first element there is a gap with the index 0. Consider an example:

b = (5, 3.6, "square", 15, 'B')

('square', 15)


Tuples in python have only two methods: index() and count(). The first is used to find out what index a particular element has. For example:

a = (32, 33, 34, 33, 34, 33)


There are several “33” elements in the tuple, but the index of the first of them will be displayed. The count method is used if you want to know how many defined elements there are in the tuple.

a = (32, 33, 34, 33, 34, 33)


The user will see exactly number 3 on the screen, because number 33 is repeated three times in the tuple. Remember that tuples do not have methods to add or remove elements.

Named tuples

This class is not widely used by programmers, although it is quite important and useful. Named tuples in python (or namedtuple) are in a sense extensions to regular ones. For example, a huge problem is that you can only retrieve data from a tuple using numeric indexes. But what if you want to refer to elements using string names for code clarity. Such a reference will significantly improve the readability of the code. For this purpose namedtuple comes to the rescue. In order to use namedtuple, you need to integrate collections library. This can be done by using the import collecions *. In this case you will need to refer to the namedtuple as follows: collections.namedtuple( [parameters] ). Another way to connect the library is in the example below. Each item stored in a named tuple is accessible through a specific identifier. Let’s look at an example of this code:

from collections import namedtuple
Flower = namedtuple('Flower' , 'color cost comment')
rose = Flower('red', 5, 'beautiful')


The field names were listed with a space. You could pass a list with strings instead of this string. In the constructor namedtuple will split the resulting string using split. As an example, the cost element was referenced. The others are treated similarly: rose.color, rose.comment. Thus, a named tuple makes the program code look more readable. For example, in the above code you can see the names color, cost, and comment. With all that said, it is still possible to refer to elements by an index, for example by adding to the previous code:



List of tuples

Sometimes you need to store tables of data, called matrices (or two-dimensional arrays). The array library is used to work with arrays. Unfortunately, you can’t use it to make an array of tuples. Because an array element cannot be a tuple. The way out of this situation is to create a tuple list in Python. A variant declaration of such a list is shown below:

a = [(1,2,3),(4,5,6)]


Sometimes you need to sort the available items in a list. Thanks to the built-in sorted function, this can be done quite easily:

a = ('One', 'Two', 'Three')
a = tuple(sorted(a))

('One', 'Three', 'Two')

You can see that Python sorted the tuple alphabetically. Standard sorting can be done on numeric elements as well. Let’s look at an example:

a = (3, 1, 5 ,2, 6, 7)
a = tuple(sorted(a))

(1, 2, 3, 5, 6, 7)

Notice that it is sorted in ascending order.

Note that the sorted function returns a list, but we use tuple to bring the result of the sorting to a tuple.

Into a list

A tuple can be converted to a list:

a = (1,2,3)
a = list(a)

[1, 2, 3]

Thus, the tuple has been converted to a Python list, which can be modified. Now consider the inverse action of converting a list into a tuple:

a = [1, 2.6, "square"]
a = tuple(a)

(1, 2.6, "square")


A dictionary is another structure used in Python. It, like a list, is changeable, but also unordered. This means that it is not possible to refer to a specific item by specifying an index. To better understand it, we can draw an analogy with the English-Russian dictionary. Each word in the dictionary has a translation: house, flat, window. If you transfer this structure to your program code, you get the following entry, made out of curly braces:

{'house': 'house', 'flat': 'apartment', 'window': 'window'}

The sequence of pairs displayed on the screen is not defined by any rule, they are displayed in any order. To convert a tuple into a dictionary in Python, you need to use a type conversion with dict.

a = (('a', 2),('b', 4))
a = dict(a)

{'a': 2, 'b': 4}

As you can see, a tuple of tuples was needed to create the dictionary. And nested tuples consist of two elements each. Otherwise the conversion to the dictionary is impossible.

Into string

To output a tuple in python to a single line, the join function is used. Let’s look at an example:

a = ('one', 'two', 'three')
b = ''.join(a)
c = ','.join(a)


After the code is executed, the display will show all elements in one line with a specified separator. In the first case, without spaces, and in the second case, with a comma. How are tuples more convenient? Working with them is faster than with lists, for example. If a programmer needs to define a fixed set of values to enumerate them later, it’s better to do it with tuples. A good thing is that they save on memory, because they take up less space than lists.

Related Posts