Tuple in Python

Python_logo_and_wordmark.svg

In this blog, we are going to discuss the tuple data structure of python.

A tuple is a collection which is immutable, we cannot change the elements of a tuple once it is assigned. It allows duplicate members i.e. (1, 1) is allowed.

Any set mutiple comma-separated symbols written default to tuples.

>>> x, y = 1, 2

Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair.

>> d = {‘a’: 10, ‘b’: 1, ‘c’: 22}

>> t = d.items()

> print(t)

[(‘a’, 10), (‘c’, 22), (‘b’, 1)]

DECLARE TUPLE

Tuple can be declared using round brackets or tuple constructor.

>>> emptytuple= ()

>>> emptylist

()

>>> type(emptytuple)

>>> emptytuple = tuple()

>>> emptytuple

[]

>>> tup = (1) # creating tuple with single element requires “,” in the end

>>> tup

1

>>> type(tup)

>>> tup = (1,)

>>> type(tup)

The syntax of tuple() constructor is:

tuple([iterable])

>>> tup = tuple(1,2)

Traceback (most recent call last):

File “”, line 1, in

TypeError: tuple() takes at most 1 argument (2 given)

>>> tup = tuple((1,2))

>>> tup

(1, 2)

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

>>> tup

(1, 2)

ACCESS ELEMENTS OF TUPLE

>>> tup = (1, 2, 3)

>>> tup[0]

1

>>> 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

ADD ELEMENTS TO TUPLE

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

>>> tup.insert(0, 10)

Tuples are immutable.

MODIFYING ELEMENTS OF TUPLE

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

>>> 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.

ITERATE ITEMS OF TUPLE

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

>>> for item in tup:

… print(item)

1

2

3

4

OPERATORS ON TUPLE

>>> 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)

DELETING 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

FUNCTIONS ON TUPLE

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

>>> tup.index(3)

2

>>> tup.count(5)

2

>>> max(tup)

5

>>> min(tup)

1

CHECK EXISTENCE OF ITEM IN TUPLE

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

>>> 1 in tup

True

>>> 7 in tup

False

DELETE  TUPLE

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

>>> del tup

ACCESSING ITEMS OF NESTED TUPLE

>>> 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}

Thanks for reading!!

Knoldus-blog-footer-image

Written by 

Jyoti Sachdeva is a software consultant with more than 6 months of experience. She likes to keep up with the trending technologies. She is familiar with languages such as C,C++,Java,Scala and is currentky working on akka,akka http and scala. Her hobbies include watching tv series and movies, reading novels and dancing.

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!