Python Tuples


Introduction to Python Tuples

Tuple is a collection of Python objects, much like a list, but it is an immutable collection. We have discussed the immutable in detail in this article.

Tuples in python are created using the parenthesis ‘()’. A tuple can hold values of any data type like integer, float, string, list, dictionary, or even the tuple itself. The comma(,) is used to separate items inside the tuple. We can create the tuple using the tuple() function as well. Let us have a look at a few examples:

Tuple with just integers.

In [1]:
first_tuple = (1,2,3,4,5)
print(first_tuple)
(1, 2, 3, 4, 5)

Tuple having a string, integer, float, and boolean.

In [2]:
second_tuple = ['string',1,13.3,True]
print(second_tuple)
['string', 1, 13.3, True]

Tuple created using tuple() function.

In [3]:
third_tuple = tuple(('string',1,13.3,True))
print(third_tuple)
('string', 1, 13.3, True)

4 Ways to Create Tuple

There are multiple ways by which tuples can be created:

  • General approach
  • Without parenthesis
  • Tuple with Single element
  • Tuple constructor

General approach : Tuple is created using parenthesis and all the elements are separated by commas.

In [1]:
marks = (75,85,91,79,82)
print(marks)
(75, 85, 91, 79, 82)

Without parenthesis : We can create a tuple without parenthesis as well. All the elements are separated by commas.

In [1]:
marks = 75,85,91,79,82
print(marks)
print(type(marks))
(75, 85, 91, 79, 82)
<class 'tuple'>

Tuple with a single item : To create a tuple with a single item only, then we need to add a comma after the item; otherwise it is not considered as a tuple.

Without comma, a single number is treated as an integer

In [1]:
marks = (75)
print(marks)
print(type(marks))
75
<class 'int'>

With comma, a single number is treated as a tuple.

In [2]:
marks = (75,)
print(marks)
print(type(marks))
(75,)
<class 'tuple'>

Tuple Constructor : Tuple constructor can also be used to create a tuple.

In [1]:
marks = tuple((75,85,91,79,82))
print(marks)
print(type(marks))
(75, 85, 91, 79, 82)
<class 'tuple'>

Characteristics of a Tuple

Let us look at the characteristics of the Tuple one by one:

CharacteristicMeaning
ImmutableThis means that we cannot change the items stored within the tuple.
Duplicate ElementsDuplicate items are allowed in the tuple.
OrderedTuples maintain the order of the items in which they are inserted.
HeterogeneousTuples can store elements of various data types.
Python Tuples

Tuples are immutable – unchangeable

Once tuples are assigned values, we cannot change any value at a specific location.

In [1]:
emp_details = ('Tim','Smith',28,True)
print(emp_details[1])
Smith

On trying to overwrite any value we get an error saying “‘tuple’ object does not support item assignment”.

In [2]:
emp_details[1] = 'Cook'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-283406d7f947> in <module>
----> 1 emp_details[1] = 'Cook'

TypeError: 'tuple' object does not support item assignment

Duplicate Elements

Similar to a list, we can have any number of duplicate elements in a tuple.

In [1]:
duplicates = ('string',1,1,1,1,1)
print(duplicates)
('string', 1, 1, 1, 1, 1)

Ordered

In Python, like a list, the tuple is also an ordered sequence, which means, items are stored in the same order in which they are inserted.

As both tuples contains same elements, so both the tuples are the same.

In [1]:
my_tuple1 = (1, 2, 3)
my_tuple2 = (1, 2, 3)
print(my_tuple1 == my_tuple2)

Now on changing the order, they are not the same.

In [2]:
my_tuple1 = (1, 2, 3)
my_tuple2 = (1, 3, 2)
print(my_tuple1 == my_tuple2)

The type() function

At any stage in our program, we may need to check if the variable is a tuple or not, we can use the type() function for this purpose. If the type of the variable is a tuple, then the type() function will return the ‘tuple’ keyword.

In [1]:
emp_details = ('Tim','Smith',28,True)
print(type(emp_details))
<class 'tuple'>

Tuple Operations

Add Items

As tuples are immutable, there is no way we can directly add items to the tuple. But we do have a workaround to do so, by converting a tuple to a list, adding an item and again converting it back to a tuple.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
namelist = list(nametuple)

namelist.insert(2, "Tom")

nametuple = tuple(namelist)
print(nametuple)
('Bill', 'Steve', 'Tom', 'Tim')

Change/Update item

As tuples are immutable, it is not possible even to change an item of a tuple, but again we can use the workaround of converting a tuple to a list, change the items of the list, and convert the list back to a tuple.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
namelist = list(nametuple)

namelist[2] =  "Tom"

nametuple = tuple(namelist)
print(nametuple)
('Bill', 'Steve', 'Tom')

Remove Items

Again, because tuples are immutable, so we cannot even remove an item from a tuple. To achieve this, we can use the same workaround of converting a tuple to a list, removing an item and then again converting it back to a tuple.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
namelist = list(nametuple)

namelist.remove("Steve")

nametuple = tuple(namelist)
print(nametuple)
('Bill', 'Tim')

Join Tuples

We simply use the + operator to join tuples.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
newnames = ("Tom", "Sam")

nametuple = nametuple + newnames
print(nametuple)
('Bill', 'Steve', 'Tim', 'Tom', 'Sam')

Delete a tuple

We use the del keyword to delete a tuple.

Once the tuple is deleted, we get the NameError saying “name ‘nametuple’ is not defined”.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
del nametuple
print(nametuple)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-c9b88b96c9c5> in <module>
      1 nametuple = ("Bill", "Steve", "Tim")
      2 del nametuple
----> 3 print(nametuple)

NameError: name 'nametuple' is not defined

Advantages and Disadvantages of Tuples

Advantages

  • Since, tuples are immutable, we can use to store some secure read-only data that we don’t want to be changed throughout our code.
  • Again, because tuples are immutable, iterating through a tuple is faster than a list.
  • Tuples can be used as a key for a dictionary. With lists, this is not possible.

Disadvantages

  • It cannot be used when we want to add or delete an item. So, it has quite limited use case.
  • Tuples provide fewer built-in methods compared to lists. Lists offer more functionality, such as adding, removing, and modifying elements, which can be a limitation when working with tuples.
  • As a tuple is stored on the heap, so it is an overhead on the garbage collector.

References

  1. Tuples in Python
  2. Data Structures