Search for Courses, Topics

Tuples in Python

Learn about Tuples in Python.

29 Nov 2021-10 mins read
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

A tuple is one of the four inbuilt data types used to store collections in Python. Unlike other data types, the elements in tuples are ordered and immutable. They are used to store multiple items in a single variable and provides some built-in operation to work with them.

Scope of article

  • In this topic, we will introduce ourselves tuples in Python.
  • We will learn how to create, modify and delete a tuple.
  • We will discuss different operations on tuple.
  • Finally, we will look at some advantages and disadvantages of the tuple.

Introduction to Tuples in Python

Python has multiple data structure collections to offer like lists, tuples, sets and dictionaries. But these tuples are pretty similar to lists. Lists being a commonly used data structure by the developers, usually confuse how tuples are different to lists.

Let’s understand tuples in python deeply and see its application, use cases and how they’re different from the commonly used data structure collection, Lists.

Well, Python tuples are a collection of elements of any data type just like lists, but tuples are immutable i.e. we cannot change the elements of the tuple or the tuple itself, once it's assigned whereas we can change the elements of the list as they are mutable.

Creating a Tuples in Python

Tuples can only be created when they are being assigned, hence placing all the elements inside the parenthesis, separated by a comma will create a tuple. Let’s take a closer look at the syntax:

tempTuple = ('apple', 'mango', 'banana')
print(tempTuple)

Output

('apple', 'mango', 'banana')  

The parenthesis in the above syntax is optional and hence a tuple can also be created without writing the parenthesis. But remember it’s always a good practice to have the parenthesis, as it always increases the code readability and understanding.

The above snippet can also be written as:

tempTuple = 'apple', 'mango', 'banana'
print(tempTuple)

Output

('apple', 'mango', 'banana')  

How to define a python tuple with a single element?

What if in the above snippet you write tempTuple = (‘apple’) OR tempTuple = ‘apple’ instead of tempTuple = (‘apple’, ‘mango’, ‘banana’) OR tempTuple = ‘apple’, ‘mango’, ‘banana’ ?

Well, python will consider it as a string, in this case, hence a trailing ‘,’ is a mandate in order for the python interpreter to interpret it as a tuple.

tempTuple = ('apple')
print(type(tempTuple)) # OUTPUT: <class ‘str’>
tempTuple = ('apple',)
print(type(tempTuple)) # OUTPUT: <class ‘tuple’>
tempTuple = 'apple',
print(type(tempTuple)) # OUTPUT: <class ‘tuple’>

Output

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

Accessing Elements in a Python Tuple and Indexing:

Accessing elements in a tuple is no different than accessing elements in a list. As python follows 0 based indexing hence a tuple with n elements will have indices from 0 through n-1. An index in a tuple is accessed with the index operator [ ]. For example:

Let’s consider a basic tuple:

tempTuple = ('hello', 1, 2, 3)
print(tempTuple[0]) # prints first element of the tuple
print(tempTuple[3]) # prints last element of the tuple
print(tempTuple[4]) # error

Nested Python Tuple Accessibility:

nestedTuple = ('hello', [1 ,2, 3], (4, 5, 6))
print(nestedTuple[0][2])
print(nestedTuple[2][2])

Accessing Via Negative Indices:

Python allows you to access elements of a collection via negative indices. When accessing using a negative index, -1 depicts the last element and -n depicts the first index where n is the length of the index.

Consider the following mapping of the positive index with negative index:

accessing tuples via negative indices

tempTuple = ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day')
print(tempTuple[2]) # interview
print(tempTuple[-6]) # interview

Updating Tuples in Python:

Adding a new element or deleting one is not really an option when dealing with tuples in python, as they are immutable. Even the elements of the tuple cannot be updated until and unless the element is mutable for example a list.
Let’s take an example

tempTuple = ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day', [1, 2, 3])
# tempTuple[0] = 'Hello' # throws type error, tuple object does not support type assignment.
tempTuple[8].append(4) # appending a new integer i.e. 4 in a list at 8th index of the tuple ‘tempTuple’
# Printing the list at 8th index in the tuple
print(tempTuple[8]) # OUTPUT: [1, 2, 3, 4]
tempTuple[8].pop(3) # popping element at 3rd index from the list i.e. 8th index of the tuple 'tempTuple'
# Printing the list at 8th index in the tuple
print(tempTuple[8]) # OUTPUT: [1, 2, 3]
tempTuple = (1, 2, 3) # Assigning tuple all over again
# Printing the tuple
print(tempTuple) # OUTPUT: (1, 2, 3)

Output:

[1,2,3,4]
[1,2,3]
(1,2,3)

Tuples in python can definitely be reassigned, which is very different from updating a tuple. Reassigning a tuple is redefining the tuple all over again.

Just like strings, we can also contact two or more tuples to form a new tuple using the ‘+’ operation or apply repetition on a tuple using the ‘*’ operator, just the result here is a python tuple and not a string.

# concatenating two different tuples
print(('apple', 'mango') + (1, 2, 3)) # OUTPUT: (‘apple’, ‘mango’, 1, 2, 3)
# repeat a tuple 5 times
print(("apple",) * 5) # OUTPUT: (‘apple’, ‘apple’, ‘apple’, ‘apple’, ‘apple’)

Output

('apple', 'mango', 1, 2, 3)
('apple', 'apple', 'apple', 'apple', 'apple')

Deleting Tuples in Python:

As discussed, python tuples being immutable cannot be updated. Hence once some values are assigned to a tuple, it cannot be deleted. You can delete a tuple as a whole, but deleting a specific value/element in a tuple is not possible. Let’s look at the example:

tempTuple = (1, 2, 3, 4, 5)
# tempTuple.pop() # throws error as object has no attribute pop
# del tempTuple[3] # throws error as tuple does not support object deletion
print(tempTuple) # OUTPUT: (1, 2, 3, 4, 5)
del tempTuple
print(tempTuple) # throws NameError: name 'tempTuple' is not defined

Output

(1,2,3,4,5)
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(tempTuple) # throws NameError: name 'tempTuple' is not defined
NameError: name 'tempTuple' is not defined

In-built Functions for Tuple:

Python has the following inbuilt functions to offer for tuples:

slicing in python tuples

Slicing in tuples:

Slicing in tuples works the same as it works for a String slicing or any other sequence of elements. Slice is an operator that allows you to fetch a sub-collection (in this case a sub tuple) from a collection by slicing it from a start index and a stop index.

Slice syntax:

Str[start : stop : step]

  • start: is the starting index of the string, on which the slicing operation has to be performed. It determines from where the slicing of the string will ‘begin’.
  • stop: is the stopping index of the slicing, ‘until’ which slicing operation has to be performed i.e stop index is excluded while generating the sub-tuple.
  • step: It is an optional argument that defines the steps when iterating the list i.e. it allows us to skip over elements.

Consider the above figure when understanding the following code snippet

temptuple =  ("Welcome", "to", "interview", "bit.", "Have", "a", "great", "day")
tuple1 = temptuple[::] # fetching complete tuple
print("tuple1:", tuple1) # OUTPUT: (‘Welcome’, ‘to’, ‘interview’, ‘bit.’, ‘Have’, ‘a’, ‘great’, ‘day’)
tuple2 = temptuple[0 : 6] # fetching tuple from 0th index to 6th index
print("tuple2:", tuple2) # OUTPUT: (‘Welcome’, ‘to’, ‘interview’, ‘bit.’, ‘Have’, ‘a’)
tuple3 = temptuple[:: 3] # jumping every third element from start to end
print("tuple3:", tuple3) # OUTPUT: (‘Welcome’, ‘bit.’, ‘great’)
tuple4 = temptuple[1:5:2] # jumping to every 2nd element starting from 1st index until 5th index
print("tuple4:", tuple4) # OUTPUT: (‘to’, ‘bit.’)
tuple5 = temptuple[-8:-5] # 8th index from end to 5th index from end
print("tuple5:", tuple5) # OUTPUT: (‘Welcome’, ‘to’, ‘interview’)
tuple6 = temptuple[::-3] # jumping every 3rd element in reverse
print("tuple6:", tuple6) # OUTPUT: (‘day’, ‘Have’, ‘to’)
tuple7 = temptuple[-7:-3:2] # alternate implementation of tuple4
print("tuple7:", tuple7) # OUTPUT: (‘to’, ‘bit.’)
 

Output

tuple1: ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day')
tuple2: ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a')
tuple3: ('Welcome', 'bit.', 'great')
tuple4: ('to', 'bit.')
tuple5: ('Welcome', 'to', 'interview')
tuple6: ('day', 'Have', 'to')
tuple7: ('to', 'bit.')

Basic Python Tuple Operations

Just like ‘+’ and ‘*’ operations, tuple also respond to other sequential operations like length, membership and for loop. Consider the following example:

tempTuple = ('apple', 'mango')
result = tempTuple + (1, 2, 3) # concatenating two different tuples
print('concatenation of a tuple', result) # OUTPUT: concatenation of a tuple (‘apple’, ‘mango’, 1, 2, 3)
result = tempTuple * 3 # repeat a tuple 3 times
print('repetition of a tuple', result) # OUTPUT: repetition of a tuple (‘apple’, ‘mango’, ‘apple’, ‘mango’, ‘apple’, ‘mango’)
result = len(tempTuple) # length of a tuple
print('length of the tuple:', result) # OUTPUT: length of the tuple: 2
result = 'apple' in tempTuple # checking membership of an element in tuple
print('membership check', result) # OUTPUT: membership check True
for fruit in tempTuple: # running for loop, as a tuple is a sequence
 print("for loop", fruit)
# OUTPUT 1st iteration: forloop apple
# OUTPUT 2nd iteration: forloop mango

Output

concatenation of a tuple ('apple', 'mango', 1, 2, 3)
repetition of a tuple ('apple', 'mango', 'apple', 'mango', 'apple', 'mango')
length of the tuple: 2
membership check True
for loop apple
for loop mango

Advantages and Disadvantages of Python Tuples:

Advantages:

  • Tuples being immutable, turns out to be a write-protected collection. Tuples can be of advantage when we want to store some secure read-only data that we cannot afford to be changed throughout our code.
  • Tuples can store data of multiple data types, which makes them a heterogeneous collection.
  • Tuple being a readonly collection, has a faster iteration. (As they are stored in a single block of memory, and don’t have extra space for storing objects, they have a constant set of values)

Disadvantages:

  • Tuple’s being write protected, is an advantage but also a disadvantage as it cannot be used when we want to add or delete a specific element. Hence has a limited use case.
  • Syntactically less readable as tuples can be created by either adding parentheses or by not providing them in case we have more than one element. But not using parentheses in the case of one element, will not create a tuple and hence a trailing comma in such case is required. This can make code readability a bit complex for some.
  • As tuple is a class, it's stored on the heap and is overhead on the garbage collector.

Tuple’s advantages and disadvantages are nothing but its use cases i.e. tuple serves some use cases hence one should know when to use a tuple, in order to use it for their advantage. Tuples when used where a list or a dictionary or a set would’ve been used, will turn out to be a disadvantage.

Conclusion:

  • Tuples are one of the data structures that python has to offer and is immutable, ordered, has integer based indexing and allows duplicate data to be stored.
  • Tuples can be created both using parentheses and comma separated elements AND without parentheses and comma separated elements. If not using parenthesis, a trailing comma should be added for python to interpret as a tuple.
  • Deleting an element from a tuple is not possible. But deleting a tuple is.
  • Overall, tuples are of advantage when used for the use case it is designed for. Similarly are of disadvantage, if used where a list, set or a dictionary should’ve been used. Hence one should analyse what their use cases are and decide corresponding data structure or collection to be used. Similarly, this is valid for all data structures.
Challenge Time!
quiz Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
certificate icon
Certificates
Python Tutorial
Module Certificate
Criteria
You’ll be able to claim a certificate for any course you have access to only after you’ve spent enough time learning. The time required is determined by the length of the course.
Certificates are a fantastic way to showcase your hard-earned skills to employers, universities, and anyone else that may be interested. They provide tangible proof that you’ve completed a course on Scaler Topics. In many cases they can help you claim a training reimbursement or get university credit for a course.