Tuples in python

Jayashree domala
2 min readSep 15, 2020

--

A guide to understanding tuples in python

In python, tuples are very similar to list. However, they have one major difference. This is the property of immutability. Immutability means not changing over time. That means that once an element is inside a tuple, it cannot be reassigned.

The syntax to represent tuples is ().

>>> tup = (11,22,33)
>>> list1 = [11,22,33]
>>> type(tup)
tuple
>>> type(list1)
list
>>> len(tup)
3

Various object types can also be included in the tuple

>>> tup2 = ('Python', 22)

Indexing

>>> tup2[0]
'Python'
>>> tup2[-1]
22

Slicing

>>> tup[0:2]
(11, 22)

Built-in methods

1) Count method

It counts the occurrences of the element of the tuple.

>>> tup3 = (1,1,2,3,3)
>>> tup3.count(1)
2

2) Index method

It returns the index position of the element. In case the element is repeated then the first occurrence index position is returned.

>>> tup3.index(1)
0
>>> tup3.index(2)
2

Immutability

>>> tup
(11, 22, 33)
>>> list1
[11, 22, 33]
>>> list1[0] = 'Python'>>> tup[0] = 'Python'
--------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-49ad9da61fd6> in <module>
----> 1 tup[0] = 'Python'
TypeError: 'tuple' object does not support item assignment

The elements in a tuple cannot be re-assigned and therefore it is giving an error. The benefit of using tuple is when you need to make sure that the values don’t change. It provides a very convenient source of data integrity.

Refer to the notebook here.

Beginner-level books to refer to learn Python:

Advance-level books to refer to learn Python:

Reach out to me: LinkedIn

Check out my other work: GitHub

--

--

Jayashree domala
Jayashree domala

Written by Jayashree domala

Self-driven woman who wishes to deliver creative and engaging ideas and solutions in the field of technology.

Responses (1)