×

Search anything:

Tuple in Python

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

Reading time: 30 minutes

Tuples are used to hold together multiple objects. Think of them as similar to lists, but without the extensive functionality that the list class gives you. One major feature of tuples is that they are immutable like strings i.e. you cannot modify tuples. It allows duplicate members i.e. (1, 1) is allowed.

Data structures are basically just that - they are structures which can hold some data together. In other words, they are used to store a collection of related data.

There are four built-in data structures in Python:

  • list
  • tuple
  • dictionary
  • set

We will discuss about tuple in this article.

Tuples are defined by specifying items separated by commas within an optional pair of parentheses. Any set mutiple comma-separated symbols written default to tuples.
Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values (i.e. the tuple of values used) will not change.

Declaration of tuple

tup = (1, 'python', 2000, 'chemistry')
tup1 = "a", "b", 1 

The empty tuple is written as two parentheses containing nothing −

tup1 = ();

To write a tuple containing a single value you have to include a comma, even though there is only one value −

tup1 = (50,);  # creating tuple with single element requires “,” in the end

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

The syntax of tuple() constructor is:

tup = tuple((1,2))
>>> tup
(1, 2)
tup = tuple([1,2]) # creating tuple from list
>>> tup
(1, 2)

Accessing tuple

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

>>> tup = (1, 2, 3)
>>> tup[0]
1

We can also use negative indexing to access the element of tuple,

>>> tup[-1] # using negative indexing
3
>>> tup[-3]
1
>>> tup[-7]
Traceback (most recent call last):
File “”, line 1, in
IndexError: tuple index out of range

Addition of elements to tuple

>>> tup = (1, 2, 3, 4)
>>> tup.insert(0, 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'insert'

Tuples are immutable which means we cannot update or change the values of tuple elements.

Modifying elements of tuple

>>> tup[0] = 7
>>> tup
Traceback (most recent call last):
File “”, line 1, in
TypeError: ‘tuple’ object does not support item assignment

You can’t modify the elements of tuples because tuples are immutable.

Iteration of elements of tuple

>>> tup = (1, 2, 3, 4)
>>> for item in tup:
… print(item)
…
1
2
3
4

Operation on tuple

we are able to take portions of existing tuples to create new tuples as the following example demonstrates

>>> tup = (1, 2, 3, 4)
>>> tupOne = (4, 5)
>>> tup + tupOne   # tuple concatenation it will create new tuple
(1, 2, 3, 4, 4, 5)
>>> tupOne * 3     # new tuple will be created
(4, 5, 4, 5, 4, 5)

Deletion of elements of tuple

>>> tup = (1, 2, 3, 4)
>>> del tup[0]
Traceback (most recent call last):
File “”, line 1, in
TypeError: ‘tuple’ object doesn’t support item deletion

As already discussed, we cannot perform any kind of modification on tuple.

Function on tuple

Some of in-built functions are used to perform some specific task on tuple. for example,

  • index() - used to find the index of the element.
  • count() - used to count the number of occurence of the element specified.
  • max() - used to find the maximum number in the tuple.
  • min() - used to find the minimum number in the tuple.
>>> tup = (1, 2, 3, 4, 5, 5)
>>> tup.index(3)
2
>>> tup.count(5)
2
>>> max(tup)
5
>>> min(tup)
1

Check on elements of tuple

To check whether a particular element is present in the given tuple or not, we use,

>>> tup = (1, 2, 3, 4, 5, 5)
>>> 1 in tup
True
>>> 7 in tup
False

Deletion of tuple

To delete the given tuple, we use

>>> tup = (1, 2, 3, 4, 5, 5)
>>> del tup

Accessing element on nested tuple

To access elements of nested tuple, i.e., 2D tuple, we use [] braces to twice with their index mentioned.

>>> old_tup
((1, 30, 3), (4, 5, 6), (7, 8, 9), (4, 4, 4), (4, 4, 4))
>>> old_tup[2][2]
9

LIST VS TUPLE

  • Tuples have structure while lists have order.
>>> tup = (1, 2)
>>> tup.sort()
Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘tuple’ object has no attribute ‘sort’
>>> tup.reverse()
Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘tuple’ object has no attribute ‘reverse’

You can’t modify the structure of tuple.

  • Tuples are faster than list. Tuples are stored in a single block of memory. Tuples are immutable so, It doesn’t require extra space to store new objects. Lists are allocated in two blocks: the fixed one with all the Python object information and a variable sized block for the data. This is the reason why creating a tuple is faster than List. Tuples load as a whole while in lists individual elements get loaded.

  • Tuples can store the elements directly inside the struct, lists on the other hand need a layer of indirection (it stores a pointer to the elements).

a = tuple(range(1000))
b = list(range(1000))
a.__sizeof__() # 8024
b.__sizeof__() # 9088
  • Tuple is hashable while list is not. Hash functions return the hash value of the object, if it has one.
>>> tup = (1, 2)
>>> hash(tup)
3713081631934410656
>>> list = [1, 2]
>>> hash(list)
Traceback (most recent call last):
File “”, line 1, in
TypeError: unhashable type: ‘list’
  • Tuples can be used as a key in dictionary as they are immutable while lists cannot be.
>>> list = [1, 2]
>>> tup = (1, 2)
>>> dict = {list: 1}
Traceback (most recent call last):
File “”, line 1, in
TypeError: unhashable type: ‘list’
>>> dict = {tup: 1}
>>> dict
{(1, 2): 1}
Tuple in Python
Share this