top of page

Python Tuple

Tuples are immutable data type. They are ordered and indexed like list and allow duplicate values.

Create a Tuple

a = ('Red', 'Green', 'Blue')

print(a)

Tuple can contain duplicate values.

a = ('Red', 'Green', 'Blue', 'Red', 'Yellow')

print(a)

Tuple are ordered and can be access using the index number.

a = ('Red', 'Green', 'Blue', 'Red', 'Yellow')

print(a[1])

Change Tuple Elements

As tuples are immutable, we cannot change them but what we can do is, we can cast the tuple first to list then change the list as per our requirement then cast it back to tuple.

Change green to black.

a = ('Red', 'Green', 'Blue')

a = list(a)

a[1] = 'black'

a = tuple(a)

print(a)

Add Tuple Elements

As tuples are immutable, we cannot add element in tuple but what we can do is, we can cast the tuple first to list then add element in the list then cast it back to tuple.

Add black at the end.

a = ('Red', 'Green', 'Blue')

a = list(a)

a.append('Black')

a = tuple(a)

print(a)

Delete Tuple Elements

As tuples are immutable, we cannot delete element in tuple but what we can do is, we can cast the tuple first to list then delete element in the list then cast it back to tuple.

Delete the second element

a = ('Red', 'Green', 'Blue')

a = list(a)

a.pop(1)

a = tuple(a)

print(a)

Delete Green

a = ('Red', 'Green', 'Blue')

a = list(a)

a.remove('Green')

a = tuple(a)

print(a)

del a

We can't change the tuple because tuple is immutable but we can delete the tuple.

Delete the Tuple.

a = ('Red', 'Green', 'Blue', 'Black')

del a

print(a)

Tuple Loop

Iterate over a Tuple.

a = ('Red', 'Green', 'Blue')

for i in a:

    print(i)

count()

Count number of time green occurs.

a = ('Red', 'Green', 'Blue', 'Green', 'Black')

b = a.count('Green')

print(b)

index()

Index number of first occurence of Green.

a = ('Red', 'Green', 'Blue', 'Green', 'Black')

b = a.index('Green')

print(b)

Tuple Functions

Length of Tuple

a = ('Red', 'Green', 'Blue', 'Green', 'Black')

print(len(a))

Maximum element in a Tuple

a = (45,65,12,97,10)

print(max(a))

Minimum element in a Tuple

a = (45,65,12,97,10)

print(min(a))

Sum of a Tuple

a = (45,65,12,97,10)

print(sum(a))

bottom of page