You Will Learn The Following Topics in This Tutorial: Chapter 16 - Tuples in Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.

com

Chapter 16 - Tuples in Python

You will Learn the Following Topics in this Tutorial


S. No. Topics
1 Introduction

2 Creating Tuple

3 A one-element tuple may be created as

4 Accessing Tuple

5 Traversing a Tuple

6 Tuple Operations

7 1) Concatenating Tuples 2) Replicating Tuples

8 3) Membership Operator in Tuple 4) Slicing

9 5) Comparing Tuple

10 Tuples are immutable

11 Add New Element To Tuple

12 Deleting A Tuple

13 Tuple Methods and Functions

14 1) len() 2) tuple() 3) count() 4) index()

15 5) sorted() 6) min() 7) max() 8) sum()

16 Nested Tuple
Example: Write a program to input n numbers from the user. Store these
numbers in a tuple. Print the maximum, minimum, sum and mean of number
17
from this tuple.

Page 1 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

INTRODUCTION
 A tuple is a sequence of values, which can be of any type and they are
indexed by integer.
 Tuples are just like list, but we can’t change values of tuples in place.
 Thus tuples are immutable. The index value of tuple starts from 0.

Creating Tuple:
i) A tuple can be created by enclosing one or more value in round
brackets ( ).

For Example:

#tuple1 is the tuple of six odd numbers


>>> tuple1 = (1,3,5,7,9,11)
>>> print(tuple1)
(1, 3, 5, 7, 9, 11)

#tuple2 is the tuple of vowels


>>> tuple2 = ('A','E','I','O','U')
>>> print(tuple2)
('A','E','I','O','U')

#tuple3 is the tuple of mixed data types


>>> tuple3 = (50, 33.5,'Hi')
>>> print(tuple3)
(50, 33.5,'Hi')

Page 2 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

#tuple4 is the tuple of tuples called nested tuple


>>> tuple4 =(('Physics',041),('Chemistry',043),
('Maths',041), ('Comp.Sc.',083))
>>> print(tuple4)
(('Physics',041),('Chemistry',043),('Maths',041),
('Comp.Sc.',083))

ii) Using other Tuples

For Example
# Here tuple5 is created as a copy of tuple1.
>>> tuple5 = tuple1 [:]
>>> print (tuple5)
(1, 3, 5, 7, 9, 11)

# create tuple having first two elements of tuple1.


>>> tuple6 = tuple1 [0:2]
>>> print (tuple6)
(1, 3)

The empty tuple:


 An empty tuple is a tuple without any value inside tuple ( ) function

and having zero length.


For Example:

>>> tupl = tuple()


>>> print ( tupl )
()
Page 3 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

A one-element tuple may be created as follows:

 If there is only a single element in a tuple then the element should be


followed by a comma.
 If we assign the value without comma it is treated as integer.
 It should be noted that a sequence without parenthesis is treated as
tuple by default.
# incorrect way of assigning single element to tuple
# tuple5 is assigned a single element
>>> tuple5 = (200)
>>> tuple5
200
>>>type(tuple5) #tuple5 is not of type tuple
<class 'int'> #it is treated as integer

# Correct Way of assigning single element to tuple


# tuple5 is assigned a single element
>>> tuple5 = (20,) #element followed by comma
>>> tuple5
(20,)
>>>type(tuple5) #tuple5 is of type tuple
<class 'tuple'>

# sequence without parentheses is treated as tuple by default


>>> seq = 1,2,3 #comma separated elements
>>> type(seq) #treated as tuple
Page 4 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

<class 'tuple'>
>>> print(seq) #seq is a tuple
(1, 2, 3)

Accessing Tuple:

The elements of a tuple are accessed in the same way as elements are
accessed in a list.
Let us understand with the help of an example:
#Access tuple with subscripts

myTuple = (3, 6, 9, 12, 15, 18, 21, 24, 27, 30)

#1) To access the first element of the tuple

print(" To access the first element: ", myTuple [0])

OUTPUT:

To access the first element: 3

#2) To access the fourth element of the tuple

print(" To access the fourth element: ",myTuple[3])

OUTPUT:

To access the fourth element: 12

#3) To access the last element of the tuple

print(" To access the last element: ",myTuple[-1])

OUTPUT:

To access the last element: 30


Page 5 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

#4) To access the third last element of the tuple

print(" To access the third last element: ",myTuple[-3])

OUTPUT:

To access the third last element: 24

Traversing a Tuple:
Traversing a tuple means accessing the elements of the tuple one after
the other by using the subscript of index value.

a) Iterating through tuple using for loop

Using for loop we can access individual element of a tuple.

For Example:

tuple1 = (3, 6, 9, 12, 15, 18, 21, 24)


for i in tuple1:
OUTPUT:
print(i, end = ',')
3, 6, 9, 12, 15, 18, 21, 24,
In the above code, the loop
starts from the first element of the tuple tuple1 and automatically ends
when the last element is accessed.

Page 6 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

b) Iterating through tuple using while loop


Using while loop we can access individual element of a tuple till the end
of the inputted tuple, which can be determined using standard library
function, len ( ) function.

For Example:

tuple1 = (3, 6, 9, 12, 15, 18, 21, 24)


i=0
while i< len(tuple1):
print (tuple1[i], end = ',')
i = i + 1
In the above code , while loop runs OUTPUT:
till the condition i < len(tuple1) is 3, 6, 9, 12, 15, 18, 21, 24,
true.

TUPLE OPERATIONS:

Tuple can be manipulated using operations like

1) Concatenate ( + )
2) Repetition / Replicating ( * )
3) Membership ( in and not in)
4) Tuple Slicing
5) Comparison Operators

Page 7 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

1) Concatenating Tuples:
Python allows us to join two or more tuples using concatenation operator
depicted by the symbol +.

#tuple1 is tuple of first five odd integers


>>> tuple1 = (1,3,5,7,9)
#tuple2 is tuple of first five even integers
>>> tuple2 = (2,4,6,8,10)
#elements of tuple1 followed by tuple2
>>> tuple1 + tuple2
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

#concatenates two tuples containing string values


>>> tuple3 = ('Red','Green','Blue')
>>> tuple4 = ('Cyan', 'Magenta', 'Yellow', 'Black')
>>> tuple3 + tuple4
('Red','Green','Blue','Cyan','Magenta','Yellow','Black')

#single element is appended to tuple6


>>> tuple6 = (1,2,3,4,5)
>>> tuple6 = tuple6 + (6,)
>>> tuple6
(1, 2, 3, 4, 5, 6)

Page 8 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

Note: If we try to concatenate a tuple with elements of some other data


type, TypeError occurs. For Example:

>>> tuple1 = (1,2,3)


>>> str1 = "abc"
>>> tuple1 + str1
TypeError: can only concatenate tuple (not "str") to tuple

2) Replicating Tuples
Python allows us to repeat the given tuple using repetition operator(*).
>>> tuple1 = ('Save')
#elements of tuple1 repeated 4 times
>>> tuple1 * 4
['Hello', 'Hello', 'Hello', 'Hello']

3) Membership Operator in Tuple

in operator:

The operator displays True if the tuple contains the given element or the
sequence of elements.
>>> tuple1 = ['C.Sc.','IP','Web App']
>>> 'IP' in tuple1
True

>>> 'Maths' in tuple1


False

Page 9 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

not in operator:

The not in operator returns True if the element is not present in the
tuple, else it returns False.
>>> tuple1 = ['C.Sc.','IP','Web App']
>>> 'IP' not in tuple1
False

>>> 'Maths' not in tuple1


True

4) Slicing
Like lists, the slicing operation can also be applied to tuples.
>>> tuple1 =('Maths','Phy','Che','Eng','IP','C.Sc.','PE')
>>> tuple1[2:6]
('Che','Eng','IP','C.Sc.')

#tuple1 is truncated to the end of the tuple


>>> tuple1[2:20] #second index is out of range
('Che','Eng','IP','C.Sc.','PE')

>>> tuple1[7:2] #first index > second index


() #results in an empty tuple

#return subtuple from index 0 to 4


>>> tuple1[:5] #first index missing
Page 10 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

('Maths','Phy','Che','Eng','IP'0
#slicing with a given step size, here step size is 2
>>> tuple1[0:6:2]
('Maths', 'Che', 'IP')

#negative indexes
#elements at index -6,-5,-4,-3 are sliced
>>> tuple1[-6:-2]
('Phy', 'Che', 'Eng', 'IP')

#both first and last index missing


>>> tuple1[::2] #step size 2 on entire tuple
('Maths', 'Che', 'IP', 'PE')

#negative step size


#whole tuple in the reverse order
>>> tuple1[::-1]

('PE', 'C.Sc.', 'IP', 'Eng', 'Che', 'Phy', 'Maths')

5) Comparing Tuple
 Python allows us to use all the relational operators on tuple like
==, >=,<=,!=,>,<
 Python will compare individual elements of each tuple.
>>> L1 = (9,11,13)
>>> L2 = (9,11,13)
>>> L3 = (1,5,3)
>>> L1 == L2
Page 11 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

True
>>> L1 == L3
False
>>> L1 < L2
False
>>> L1 < L3
False
>>> L4 = (9,11,15)
>>>L1 < L4
True

Tuples are immutable

Tuples are immutable means that the contents of the tuple cannot be
changed after it is created.
Let us understand the concept of mutability with help of an example.
Example
>>> tuple1 =('Maths','Phy','Che','Eng','IP','C.Sc.','PE')
>>> tuple1[2] = 'Music'
TypeError: 'tuple' object does not support item assignment
Python does not allow the programmer to change an element in a tuple
and it gives a TypeError as shown in the above example.

Page 12 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

Add new element to Tuple


1) We can add new element to tuple using + operator.
For Example:
>>> t = (100, 200, 300, 400)
>>> t = t + (600,) # this will do modification of t.
>>> print (t)
(100, 200, 300, 400, 600)
Example: Write a program to input ‘n’ numbers and store it in tuple.
Code
t = tuple()
n = int(input("Enter any number"))
print (" Enter all numbers one after other: ")
for i in range(n):
a = int(input("enter number"))
t = t + (a,)
print ("output is")
print (t)
OUTPUT:
Enter any number5
Enter all numbers one after other:
enter number10
enter number15
enter number20
enter number25
enter number30
Page 13 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

output is
(10, 15, 20, 25, 30)
2) We can also add new element to tuple by using list:-
Following example illustrates how to add new elements to tuple using a
list.
>>> T = tuple() # create empty tuple
>>> print (T)
()
>>> l = list(T) # convert tuple into list
>>> l.append(10) # Add new elements 10 to list
>>> l.append(20) # Add new elements 20 to list
>>> T=tuple(l) # convert list into tuple
>>> print (T) # Display tuple T
(10, 20)

DELETING A TUPLE:
The del statement is used to delete a tuple.
>>> T = 1,2,3,4,
>>> print (T)
(1,2,3,4)
>>> del T
>>> print (T)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print (T)

Page 14 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

NameError: name 'T' is not defined

Tuple Methods and Functions

1) len():
It returns the length of the tuple passed as the argument
>>> tuple1 = (10,20,30,40,50)
>>> len(tuple1)
5

2) tuple():

It creates an empty tuple if no argument is passed


>>> tuple1 = tuple()
>>> tuple1
[ ]
It also creates a tuple if a sequence is passed as an argument
>>> str1 = 'aeiou'
>>> tuple1 = tuple(str1)
>>> tuple1
('a', 'e', 'i', 'o', 'u')

3) count():

Returns the number of times a given element appears in the tuple


>>> tuple1 = (10,20,30,10,40,10)
>>> tuple1.count(10)
Page 15 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

3
>>> tuple1.count(90)
0

4) index():

Returns index of the first occurrence of the element in the tuple. If the
element is not present, ValueError is generated
>>> tuple1 = (10,20,30,20,40,10)
>>> tuple1.index(20)
1
>>> tuple1.index(90)
ValueError: 90 is not in tuple

5) sorted():

Takes elements in the tuple and returns a new sorted list. It should be
noted that, sorted() does not make any change to the original tuple.
>>> tuple1 =('Maths','Phy','Che','Eng','IP','C.Sc.','PE')
>>> sorted(tuple1)
>>> tuple1
['C.Sc.', 'Che', 'Eng', 'IP', 'Maths', 'PE', 'Phy']

6) min():
Returns minimum or smallest element of the tuple
>>> tuple1 = (34,12,63,39,92,44)

Page 16 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

>>> min(tuple1)
12

7) max():
Returns maximum or largest element of the tuple
>>> tuple1 = (34,12,63,39,92,44)
>>> max(tuple1)
92

8) sum():

Returns sum of the elements of the tuple


>>> tuple1 = (34,12,63,39,92,44)
>>> sum(tuple1)
284

Nested Tuple:
When a tuple appears as an element of another tuple, it is called a nested
tuple.
>>> tuple1 = (1,2,'a','c',(6,7,8),4,9)
#fifth element of tuple is also a tuple
>>> tuple1[4]
[6, 7, 8]

Page 17 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

To access the element of the nested tuple of tuple1, we have to specify


two indices tuple1[i][j]. The first index I will take us to the desired nested
tuple and second index j will take us to the desired element in that nested
tuple.

>>> tuple1[4][1]
7
#index i gives the fifth element of tuple1 which is a
tuple
# index j gives the second element in the nested tuple

Example: Write a program to input n numbers from the user. Store


these numbers in a tuple. Print the maximum, minimum, sum and mean
of number from this tuple.
numbers = tuple() #create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input())
#it will assign numbers entered by user to tuple 'numbers'
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is: ")
print(max(numbers))
Page 18 of 19
Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.com

Chapter 16 - Tuples in Python

print("The minimum number is: ")


print(min(numbers))
print("The sum of numbers is: ")
print(sum(numbers))
print("The mean of numbers is: ")
mean = sum(numbers)/(i+1)
print(mean)
ele=int(input("Enter the element to be searched: "))
if ele in numbers:
print("Element found")
else:
print("Element not found")
OUTPUT:
How many numbers you want to enter?: 5
4
6
2
8
1
The numbers in the tuple are:
(4, 6, 2, 8, 1)
The maximum number is:
8
The minimum number is:
1
The sum of numbers is:
21
The mean of numbers is:
4.2
Enter the element to be searched: 2
Element found

Page 19 of 19

You might also like