Tuples in Python with Examples

Tuples in Python: A tuple is a collection of elements or objects which is ordered and they are immutable (cannot be changed). It is same as that of lists, but there are some little differences between tuple and lists. Lists are mutable but tuples are immutable.
Lists are represented by square brackets [] whereas tuples are represented using round brackets (). The elements of tuples are separated by comma (,) same as that in lists.

Syntax:

# Syntax-1
tuple1 = ('english','java','python')

#Syntax-2
tuple2 = (1,2,3,4)

#Syntax-3
tuple3 = "a","b","c" 

Example 1: Creating an empty tuple with no data or elements:

#Example of Empty Tuple
tuple1 = ()

Example 2: Creating a tuple with only one element. Always remember that even if we create a tuple with a single element, we need to write a comma (,) at the end necessarily. Follow below given example:

#Example of creating tuple with single element
tuple1 = (21,)
print(tuple1)

# output
21

 

tuples-in-python

1). Accessing Tuple Values: To access the values or elements of tuples we can use square brackets [], same as that we used in lists. We will use the concepts of indexing along with square brackets similarly we did in lists.

tuples in python

Example

#Accessing values in tuple

tuple1 = ("Apple","Banana","Mango")
tuple2 = (23,34,56)
print("Element at index 1 is: ",tuple1[1])
print("Element at index 2 is: ",tuple2[2])

#output
#Element at index 1 is: Banana
#Element at index 2 is: 56

2). Updating Values in TuplesAs we already discussed that tuples are immutable, which means we cannot change the values or elements of tuples. We can create a tuple by using the other tuples:

Example

tuple1 = ("Apple","Banana","Mango")
tuple2 = (1,2,3)

Important: The following action is not valid for a tuple.

tuple1[0] = "Oranges"

# creating new tuple
tuple3 = tuple1 + tuple2
print(tuple3)

# output
# ('Apple','Banana','Mango',1,2,3)

Explanation:

  • As already discussed, tuples are immutable so that we cannot change or update the values of tuples.
  • So, in the very first step i.e. tuple1[0] = “Oranges” we are trying to update the value of the tuple at index zero. Which is not possible and it will return an error.
  • In the next step, we created a new tuple3 by joining tuple1 and tuple2.
  • Hence the output is displayed.

3). Deleting Tuple ElementsWe can delete the complete tuple. But deleting or removing individual elements of a tuple is not allowed. Let’s have an example to understand it better.

Example 1: For deleting complete tuple.

#Deleting Tuple
tuple1 = (1,2,3,4,5)
print(tuple1)

# output
# (1,2,3,4,5)

# deleting tuple
del(tuple1)
print(tuple1)

# Traceback (most recent call last):
#  File "test.py", line 9, in <module>
#     print tuple1;
# NameError: name 'tuple1' is not defined

Explanation:

  • Here first we have created a tuple tuple1 and assigned it with some values.
  • Then, we printed the tuple and hence the output is displayed.
  • In the next step, we deleted the tuple using the del() method.
  • Now, when we tried to print the deleted tuple. It returned an error as tuple1 is not defined.
  • It means that tuple1 does not exist. Hence we have successfully deleted the tuple.

Example 2: For deleting elements of a tuple.

x = ("Learn","Python",23, 24)
del(x[2])

# output
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
del(x[2])
TypeError: 'tuple' object doesn't support item deletion

Explanation:

  • In the first line, we created a tuple with some elements assigned to it.
  • Next, we tried to delete an element of tuple x which is at index 2 i.e 23.
  • But it returned an error as output defining that tuple object doesn’t support item deletion.
  • Hence it is cleared that the tuple is immutable and it doesn’t allow deletion of item or element.

4). Operations on TuplesThe Arithmetic operation for  + and * in a tuple is very similar to strings. It means concatenation and repetition here too. The output or result is always a new tuple, not a string.

Expression Result Description
len((3,2,1,0)) 4 Length
(3,2,4) + (3,5,7,8) (3, 2, 4, 3, 5, 7,8) Concatenation
(‘Hello!’,) * 2 (‘Hello!’, ‘Hello!’) Repetition
5 in (1, 2, 3) False Membership
for x in (4, 2, 1): print x, 4,2,1 Iteration
# tuple concatenation
x = (23, 34, 21, 45)
y = (22, 24, 90)
print("Concatenation of x and y: ",x + y)

# tuple repetition
a = ("Python Lobby Tutorials ")
print("Repetition of x and y: ",a * 2)

# tuple length
print("length of tuple x is: ", len(x))
print("length of tuple y is: ", len(y))

# output
# Concatenation of x and y: (23, 34, 21, 45, 22, 24, 90)
# Repetition of x and y: Python Lobby Tutorials Python Lobby Tutorials 
# length of tuple x is: 4
# length of tuple y is: 3

Explanation:

  • Here in this example, we have elaborated the use of operators in tuples.
  • It is the same as that we used in the List.
  • Operator + is used for concatenation and * is used for repetition of string value elements of the tuple.
  • Hence the above output is obtained.

5). Slicing, Matrices and Indexing Operations on Tuples

Tuples support some other operations also that we used to perform on lists. These operations include Indexing, Slicing and Matrices operations.

Example 1:

Let’s suppose we have a tuple:

tuple1 = ("India","Australia","Germany")

The below table shows the operations we can perform on a tuple:

Expression Results Description
tuple1[1] ‘Australia’ Offsets start at zero
tuple1[1:] [‘Australia’, ‘Germany’] Slicing fetches sections
tuple1[-1] ‘Germany’ Negative: count from the right

6). Some Built-in Tuple functions:

Python comes with some built-in useful tuple functions that reduce the programming efforts for programmers and increases the scope of tuples:

Sr no. Function Description
1 max(tuple) It returns item from the tuple with max value.
2 tuple(seq) It converts a list into tuple.
3 cmp(tuple1, tuple2) Compares elements of both tuples.
4 min(tuple) Returns item from the tuple with min value.
5 len(tuple) It returns the total length of the tuple.

Example 1:

>>> tuple1 = (1,20,4,54,3,1)
>>> max(tuple1)
54
>>> x = [1,34,"PythonLobby",55]
>>> x
[1, 34, 'PythonLobby', 55]
>>> tuple(x)
(1, 34, 'PythonLobby', 55)
>>> min(tuple1)
1
>>> len(tuple1)
6

Explanation:

  • In the first step, we created a tuple tuple1 and initialized it with some values/elements.
  • Next, we used the max() method to find the element having maximum values in the tuple sequence.
  • Now we created a list x and initialized it with some values/elements.
  • Using the tuple() method we converted the list into a tuple. We can see that we have obtained two different output one is in a list format and the second is in tuple format.
  • Next, we obtained the minimum value in the sequence of tuple and also the length of the tuple using min() and len() method of tuple respectively.