top of page

Python Tuples

 

Table of Contents

Tuples: Introduction

Creating a Tuple

Traversing Tuples

Deleting a Tuple

Tuple Operations

  • Concatenation

  • Replicating Tuples

  • Membership Operators

Nesting Tuples

Tuple Slicing

Using Relational Operators with Tuples

Built in Tuple Methods

  • len()

  • max()

  • min()

  • index()

  • count()

  • any()

  • sum()

  • tuple()

  • sorted()

Sample Programs

Tuples are a data structure in Python similar to a list. There are two basic differences:

1. Tuples are enclosed in round(()) brackets,

2. Tuples are immutable(cannot be changed) unlike lists. 

Tuples consist of elements separated by a comma. The values in a Tuple may be of the same or different types. All the operations performed on a list also apply to tuples except operations that insert, update and delete elements from a tuple.

Examples of Tuples:

 

 

 

Creating tuples

A tuple can be created by simply assigning a comma separated list of values enclosed in round brackets to an identifier.(brackets are optional)

>>>a=(22, 90, 60, 85)

 This statement creates a tuple with 4 elements.

Alternatively, we can use a function , tuple() to create a tuple. 

>>>MyTuple= tuple()

>>>pritn(MyTuple)

()

>>>T1=tuple(24,56,"Good","Deed")

>>>print(T1)

(24,56,"Good","Deed")

     

We can create a tuple at run-time by accepting values using a while loop.

Code to create a tuple from user input values:

Traversing a Tuple

We can traverse or visit each element of a tuple using a loop. 

Example:

>>> t=("Preeti","Anamika", "Aditya", "Paalguni","Paru", "Aditya", "Aditya", "Kartik", "Pulkit","Aditya")

>>> for i in t:
               print(i)

   
Preeti
Anamika
Aditya
Paalguni
Paru
Aditya
Aditya
Kartik
Pulkit
Aditya

Example:

>>> x=(22,44,11,77,88,99,33,66,99)
>>> l=len(x)
>>> for i in range(l):
   print(x[i])

    
22
44
11
77
88
99
33
66
99

Deleting a Tuple

To delete a tuple, we can simply use the del statement.

Example:

>>> x=(22,44,11,77,88,99,33,66,99)
>>> del x
>>> x
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    x
NameError: name 'x' is not defined

 

Tuple Operations

1. Joining tuples using + operator

When we use the + operator , we can easily concatenate tuples. 

Example:

>>> t1=(24,78,65)
>>> t2=(22.4,56,7)
>>> t1+t2
(24, 78, 65, 22.4, 56, 7)
>>> s1=("Good","Bad","Ugly")
>>> s2=("A1","B2","c3")
>>> s1+s2
('Good', 'Bad', 'Ugly', 'A1', 'B2', 'c3')

The + operator requires both the operands to be of type tuple. We cannot simply add values without brackets as we could do in lists.

Example 1: adding a number to an integer tuple

>>> t1=(20,25,60,90)
>>> t1+45
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    t1+45
TypeError: can only concatenate tuple (not "int") to tuple

 

Example 2: Adding an str to a string tuple

>>> s2+"D4"
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    s2+"D4"
TypeError: can only concatenate tuple (not "str") to tuple

 

Example 3:

>>> t1+(45)
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    t1+(45)
TypeError: can only concatenate tuple (not "int") to tuple

 

Explanation : This will generate an error because (45) here is considered as an integer.

Example 4 : Adding a singleton tuple

>>> t1+(45,)                 #note the comma after 45 which makes it a tuple.
(20, 25, 60, 90, 45)

2. Using '*' operator to replicate Tuples

We can use the '*' operator to replicate a tuple.

Example:

>>> ("Good", "Exciting")*2
('Good', 'Exciting', 'Good', 'Exciting')

3. Tuple Membership 

The in and not in operators can be used to check if a value is present in a tuple or not.

Example(in):

>>> t1=("Open", 90, 'J', 45.56)
>>> 90 in t1
True

>>> "Good" in t1
False

Example(not in):

>>> "Cool" not in t1
True
>>> 45.56 not in t1
False

Nesting Tuples

We can create a tuple by embedding existing tuples. This is known as nesting of tuples.

Example:

>>> t1=(9,4)
>>> t2=(22,(t1))
>>> t2
(22, (9, 4))

In the above example t1 is embedded in tuple t2.

Tuple Slicing

Just as in strings and lists tuples can be sliced. All the slicing variations work for tuples in the same manner.

Examples:

>>> t1=(20,30,40,50,60,70)
>>> print(t1[2:4])
(40, 50)


>>> t2=("python programming")
>>> t2[4:7]
'on '


>>> t2[2:9:2]
'to r'

>>> t2=(34,44,55,66,77,88)
>>> t2[::1]
(34, 44, 55, 66, 77, 88)


>>> t2[2:]
(55, 66, 77, 88)


>>> t2[2::]
(55, 66, 77, 88)


>>> t2[:4:]
(34, 44, 55, 66)


>>> t2[4:0:-1]
(77, 66, 55, 44)

Using relational operators to compare tuples.

Tuples can be compared using the operators, >, <, ==, !=, <=,>=. Python compares the tuples element by element.

Examples:

>>> t1=(22,33,44,55,66,77)
>>> t2=(25,35,45,65,75,85)
>>> t1>t2
False

>>> t2>t1
True


>>> t1=(90,20)
>>> t2=(20,90)
>>> t1>t2
True
>>> t2>t1
False


>>> t1==t2
False
>>> t1!=t2
True

We can compare string tuples in a similar way :

>>> t1=("Good", "Bad")
>>> t2=("good","bad")
>>> t1>t2
False
>>> t1<t2
True

Note : String values are compared lexicographic ally as in string comparisons.

Comparing tuples of different datatypes however will generate an error.

>>>t1=("Good","Ugly")

>>> t3=(22,44)
>>> t1>t3
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    t1>t3
TypeError: '>' not supported between instances of 'str' and 'int'

Tuples having elements of different data types can however be compared. the elements are compared one at a time. In the example below the numbers 22 and 44 are compared first followed by the strings.

Example:

>>> t1=(22,"Hello")
>>> t2=(44, "Ugly")
>>> t1>t2
False

However such comparison is nly possible if both the tuples have elements of similar data types in the same order. 

Example:

>>> t1=(22,"Hello")

>>> t3=("Good",67)
>>> t1<t3
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    t1<t3
TypeError: '<' not supported between instances of 'int' and 'str'

 

In the example above the position of the number and the string values are not same within the tuple. Thus comparing these two will generate an error. 

Tuple functions and methods

 

1. len()

Returns the number of elements in the tuple.

Example:

 

>>>t1=(1,”Preeti”,90,”XII-C”)

>>>len(t1)

4

2. max()

 

Returns the element with the maximum value in a tuple

Example:

>>>t1=(90,22,45,44,88,99)

>>>max(t1)

99

 

>>>t1=(“assemble”, “Gather”, ”Collect”,”convene”)

>>>max(t1)

convene

This is possible only if all the elements of the tuple are of the same data type otherwise, an error will be generated.

 

Example:

>>> t1=(22,"Hello")

>>> max(t1)

Traceback (most recent call last):

  File "<pyshell#29>", line 1, in <module>

    max(t1)

TypeError: '>' not supported between instances of 'str' and 'int'

 

3. min()

Returns the element with the minimum value in a tuple

Example:

 

>>>t1=(90,22,45,44,88,99)

>>>min(t1)

22

 

>>>t1=(“assemble”, “Gather”, ”Collect”, ”convene”)

>>>min(t1)

collect

 

The same rule applies to the min() function, it returns minimum value only if all the elements are of the same datatype

 

4. index()

Returns the positional value of an element in the tuple. Indexing starts at 0.

>>> t1=(22,33,44,55,66,88)

>>> t1.index(44)

2

 

The index function returns an error if the given element is not in the list:

 

>>> t1=(22,33,44,55,66,88)

>>> t1.index(90)

Traceback (most recent call last):

  File "<pyshell#39>", line 1, in <module>

    t1.index(90)

ValueError: tuple.index(x): x not in tuple

5. count()

It is used to count the number of occurrences of an item in the tuple.

Example:

>>> t=("Preeti","Anamika", "Aditya", "Paalguni","Paru", "Aditya", "Aditya", "Kartik", "Pulkit","Aditya")
>>> t.count("Aditya")
4

6. any()

This checks if the tuple is non empty. It means it returns True if there is at least if item in the tuple. It returns false if the tuple is empty.

Example:

>>>t=(45,)

>>>any(t)

True

>>>t=()

>>>any(t)

False

7. sum()

The sum() function returns the sum of all the lements in a tuple. The elements need to be of the same data type.

Example:

>>> t1=(90,35,89,22)
>>> print(sum(t1))
236

Also the sum function can be used for only numeric values. Adding non-numeric values generate an error.

Example:

>>> print(sum(t2))
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    print(sum(t2))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

8. tuple()

The tuple() function is use to convert a list into a tuple.

Example:

>>> list1=["Hello", 90,"Renting",99.99]
>>> print(tuple(list1))
('Hello', 90, 'Renting', 99.99)

9. sorted()

This is a very interesting function. It sorts a tuple and returns a list after sorting. The original tuple remains as it is i.e. the sequence of elements does not change in it.

Example:

>>> t=("Preeti","Anamika", "Aditya", "Paalguni","Paru", "Aditya", "Aditya", "Kartik", "Pulkit","Aditya")
>>> sorted(t)
['Aditya', 'Aditya', 'Aditya', 'Aditya', 'Anamika', 'Kartik', 'Paalguni', 'Paru', 'Preeti', 'Pulkit']

 

Note: The square brackets indicate that this is a list

>>> t
('Preeti', 'Anamika', 'Aditya', 'Paalguni', 'Paru', 'Aditya', 'Aditya', 'Kartik', 'Pulkit', 'Aditya')

The tuple maintains its original order.

>>>t=(9,2,4,15)                                        # pure numeric tuple

>>>tup=("Priyanka",90.5, 22, "XII","A")      # tuple with heterogeneous(different data types) values

>>>t=((22,44,77),(9,6,8))                         #nested tuples

>>>d=(["Good","morning],22,44)               # a list within a tuple with integers

>>>tup=('p','t','h','o','n',[6,7,8])                 #characters and a list in a tuple

>>>tup=()                                                #Empty tuple

>>>tup=(90,)                                           #tuple having one element only

Note: If a tuple contains a single element then the value must be followed by a comma(,), otherwise it is treated as a simple data type like integer, character e.t.c.

 

t1=tuple()
x=int(input("Enter no of elements to be input"))
i=0
while i<x:
    e=input("Enter element :")
    t1=t1+(e,)
    i=i+1
print("Tuple is", t1)

Sample Run:

>>> 
== RESTART: C:/Users/Neeru/AppData/Local/Programs/Python/Python36-32/tt.py ==
Enter no of elements to be input4
Enter element :22
Enter element :kello
Enter element :34.5
Enter element :a
Tuple is ('22', 'kello', '34.5', 'a')

Introduction
Creating Tuples
Traversing Tuples
Deleting a Tuple
Tuple Operations
Nesting Tuple
Tuple Slicing
Using Relational Operators with Tuples
Tuple functions and Methods
bottom of page