Tuples in python; the immutable data type



Introduction

Tuples in Python are a sequence or ordered data type similar to List, it supports indexing and slicing. It is an immutable data type which means its item cannot be changed once declared. However, it is possible to create tuples that contain mutable objects, such as lists.

How to create tuple?

To create a tuple we use parentheses and commas to separate elements.

For example:

animal = ('cat', 'dog', 'cow')
print(animal)
print(type(animal)) # checking data type of an animal

Output:

('cat', 'dog', 'cow')
<class 'tuple'>

A special problem is the construction of tuples containing 0 or 1 items: Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma.

Example:

tuple1 = tuple()
print(type(tuple1))
tuple2 = ('cat',)
print(type(tuple2))

Output:

<class 'tuple'>
<class 'tuple'>

Tuple is immutable but it can contain a mutable objects such as list:

Example:

x = (2, 3, 4.6,'Bhutan', ['a', 'b', 8, 7.8])
print(x)
print(type(x))

Output:

(2, 3, 4.6, 'Bhutan', ['a', 'b', 8, 7.8])
<class 'tuple'>


Nested tuple

We can create nested tuple; tuple within tuple.

Example:

fruits = ('Mango', 'Banana', 'Apple')
more_fruits = ('Guava', 'Peach', fruits)
print("Fruits list =", more_fruits)

Output:

Fruits list = ('Guava', 'Peach', ('Mango', 'Banana', 'Apple'))



Immutable tuple

The key difference between List and Tuple is that Tuple is Immutable. Its value cannot be modified or changed once declared.

Example:

fruits = ('Mango', 'Banana', 'Apple')
fruits[1]='Guava'
print(fruits)

Output:

TypeError: 'tuple' object does not support item assignment

To make the tuple mutable, we have to change it to mutable data type such as List.

Example:

fruits = ('Mango', 'Banana', 'Apple')
fru = list(fruits) #converting tuple into list
fru[1] = 'Guava'
print(fru)

Output:

['Mango', 'Guava', 'Apple'] #Output is a list

How to access tuple element?

There are two ways in which we can access the elements of a tuple:

  1. indexing
  2. slicing
Indexing

You can access tuple items by referring to the index number inside square brackets

Example 1:

animal = ('cow', 'cat', 'dog')
print("The second animal is a",animal[1]) #positive indexing
print("The last animal is a", animal[-1])  #negative indexing

Output:

The second animal is a cat
The last animal is a dog

Example 2:

animals = ('cow', 'cat', 'dog',[1,2,3,'Tiger'])
print("The third animal of index 3 in the animal's list is a",animals[3][3]) #positive indexing

Output:

The third animal of index 3 in the animal's list is a Tiger

Slicing

We can access a range of items in a tuple by using the slicing operator colon (:).

Example:

days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
print("A day starting at index 1 and ending at index 3: ",days[1:3])

Output:

A day starting at index 1 and ending at index 3:  ('Tuesday', 'Wednesday')



Tuple operation:
Iterating through a tuple

We can iterate through each item in a tuple using a for loop.

Example:

days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
for day in days:
    print(day, end = ' ')

Output:

Monday Tuesday Wednesday Thursday Friday Saturday Sunday 

Checking a membership

We can use keyword in to check the presence of items in the tuple.

Example:

days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
if 'Monday' in days:
    print("Monday is in the list of days")

Output:

Monday is in the list of days
Concatenation

Same like list data type, tuple can be also concatenated (combined).

Example:

t1 = ('Learning', 'Python')
t2 = ('made', 'EASY')
t3 = t1 + t2 #concatenating t1 and t2
print(t3)

Output:

('Learning', 'Python', 'made', 'EASY')

Repetition

Elements inside the tuple can be repeated.

Example:

lang = ('Python',)
print(lang*3)

Output:

('Python', 'Python', 'Python')



Tuple methods

Tuple supports only two methods that is count() and index().

count()

Returns the number of occurrences of items in the tuple.

Example:

number = (1,2,3,5,6,3,2,3,3)
print("Number 3 occurred = ",number.count(3),"times")

Output:

Number 3 occurred =  4 times
index()

Searches the tuple for a specified value and returns the position of where it was found. Raises ValueError if the value is not present.

Example:

number = (1,2,3,5,6,3,2,3,3)
print("The value 5 is at index", number.index(5))

Output:

The value 5 is at index 3

Functions that can be used with tuple
len()

Used to find the length of the tuple.

Example:

num = (1,2,3,6.0,'python')
print("Length of the tuple num =",len(num))

Output:

Length of the tuple num = 5
min()

Returns the minimum value.

Example:

num = (1,2,3,6)
print("The minimum value =",min(num))

Output:

The minimum value = 1

max()

Returns the maximum value.

Example:

num = (1,2,3,6)
print("The maximum value =",max(num))

Output:

The maximum value = 6


Advantage of tuple over list
  • A tuple is faster and more efficient than a list. Python uses a process called constant folding. This means recognizing and evaluating constant expressions at compile time rather than computing them at run time;
  • One important remark is that tuples are really efficient when they contain immutable objects like numbers, strings, or other tuples.
  • Tuples are safer than lists. This is called data integrity.
  • Tuples in python can be used as keys in dictionaries. Lists are not valid as keys.
  • Storage efficiency. Less memory consumption