0% found this document useful (0 votes)
372 views

Tuples

Here are the steps to solve this problem: 1. Define a function called circle that takes radius (r) as a parameter. 2. Inside the function, calculate area of circle using formula: area = πr^2 3. Calculate circumference of circle using formula: circumference = 2πr 4. Return both area and circumference as a tuple from the function. 5. Take radius as input from user. 6. Call circle function by passing radius and store the returned tuple in two variables to extract area and circumference. 7. Print the calculated area and circumference. def circle(r): area = 3.14*r*r circumference = 2*

Uploaded by

Sharang Pagotra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
372 views

Tuples

Here are the steps to solve this problem: 1. Define a function called circle that takes radius (r) as a parameter. 2. Inside the function, calculate area of circle using formula: area = πr^2 3. Calculate circumference of circle using formula: circumference = 2πr 4. Return both area and circumference as a tuple from the function. 5. Take radius as input from user. 6. Call circle function by passing radius and store the returned tuple in two variables to extract area and circumference. 7. Print the calculated area and circumference. def circle(r): area = 3.14*r*r circumference = 2*

Uploaded by

Sharang Pagotra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

TUPLES

Similar to list, data type tuple is an ordered sequence of one or more items or elements of
different types such as integer, float, string, list or even a tuple.

Elements of a tuple are enclosed in round brackets and are separated by comma.

Like list and string, elements of a tuple can be accessed using index values, starting from 0.

The only difference between list and tuple is that while list is mutable, tuple is immutable.

For Example:
#tuple1 is the tuple of integers
>>> tuple1 = (1,2,3,4,5)
>>> tuple1
(1, 2, 3, 4, 5)

#tuple2 is the tuple of mixed data types


>>> tuple2 = ('Economics',87,'Accountancy',89.6)
>>> tuple2
('Economics', 87, 'Accountancy', 89.6)
TUPLES
#tuple3 is the tuple with list as an element
>>> tuple3 = (10,20,30,[40,50])
>>> tuple3
(10, 20, 30, [40, 50])

#tuple4 is the tuple with tuple as an element


>>> tuple4 = (1,2,3,4,5,(10,20))
>>>tuple4
(1, 2, 3, 4, 5, (10, 20))

#a sequence without parentheses is treated as tuple by default


>>> seq = 1,2,3 #comma separated elements
>>> type(seq) #treated as tuple
<class 'tuple'>
>>> print(seq) # seq is a tuple
(1, 2, 3)
Accessing Elements in a Tuple
The items/elements of the tuple can be accessed in the same way as list or string using indexing and
slicing.

>>> tuple1 = (2,4,6,8,10,12) #initializes a tuple tuple1

>>> tuple1[0] #gives the first element of tuple1


2
>>> tuple1[3] #gives fourth element of tuple1
8

>>> tuple1[15] #gives error as index is out of range


IndexError: tuple index out of range

>>> tuple1[1+4] #an expression resulting in an integer index


12
>>> tuple1[-1] #gives first element from right
12
Tuple is Immutable
Tuple is a immutable data type, means the contents of the tuple cannot be changed after it
has been created. An attempt to do this would lead to an error.

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


>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment

However an element of a tuple may be of mutable type e.g. list.

>>> tupl2 = (1,2,3,[8,9]) #4th element of the tuple2 is a list


>>> tuple2[3][1] = 10 #modify the list element
>>> tuple2
(1, 2, 3, [8, 10]) #modification is reflected in tuple2
Tuple Operations: Concatenation
Python allows us to join tuples using concatenation operator plus ( + ).
>>> tuple1 = (1,3,5,7,9)
>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2 #concatenates two tuples
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

We can also create a new tuple which contains the result of this concatenation
operation.
>>> tuple3 = ('Red','Green','Blue')
>>> tuple4 = ('Cyan', 'Magenta', 'Yellow' ,'Black')
>>> tuple5 = tuple3 + tuple4
>>> tuple5
('Red','Green','Blue','Cyan','Magenta','Yellow','Black')
Tuple Operations: Repetition
We can repeat a tuple elements. The repetition operator requires the first operand
to be a tuple and second operand to be integer only.
>>> tuple1 = ('Hello',)
>>> tuple1 * 4 #replicates tuple1 four times
('Hello', 'Hello', 'Hello', 'Hello')

Tuple Operations: Membership


The ‘in’ operator checks if the element is present in the tuple and returns ‘True’ else
returns ‘False’.
>>> tuple1 = ('Red','Green','Blue')
>>>'Green' in tuple1
True

The ‘not in’ operator returns ‘True’ if the element is not present in the tuple else it
returns ‘False’.
>>> tuple1 = ('Red','Green','Blue')
>>>'Green' not in tuple1
False
Tuple Operations: Slicing
Like string and list, slicing can be applied to tuples also.
>>> tuple1 = (10,20,30,40,50,60,70,80) #tuple1 is a tuple
>>> tuple1[2:7] #elements from index 2 to index 6
(30, 40, 50, 60, 70)

>>> tuple1[0:len(tuple1)] #all elements of tuple are printed


(10, 20, 30, 40, 50, 60, 70, 80)
>>> tuple1[:5] #first index ignored,slice starts from zero index
(10, 20, 30, 40, 50)

>>> tuple1[2:] #second index is ignored ,slice is till end of the


tuple
(30, 40, 50, 60, 70, 80)
>>> tuple1[0:len(T):2] #step size 2
(10, 30, 50, 70)
>>> tuple1[-6:-4] #negative indexing
(30, 40)
>>> tuple1[::-1] #whole tuple in reverse order
(80, 70, 60, 50, 40, 30, 20, 10)
Method Description Example
tuple() ● Creates an empty tuple if no >>> T=tuple()
argument is passed >>> T
● Creates a tuple if a sequence is passed as
( )
argument >>> T1=tuple('aeiou')
#string
>>> T1
('a', 'e', 'i', 'o', 'u')
>>> T2=tuple([1,2,3]) #list
>>> T2
(1, 2, 3)
>>> T3=tuple(range(5))
>>> T3
(0, 1, 2, 3, 4)
count() Returns number of times the given element >>>
appears in the tuple T=(10,20,30,10,40,10,50)
>>> T.count(10)
3
>>> T.count(90)
0
Method Description Example
index() Returns the index of the first occurrence of the >>> T = (10,20,30,40,50)
element in the given tuple >>> T.index(30)
2
>>> T.index(90)
ValueError: tuple.index(x):
x not in tuple
sorted() Take elements in the tuple and return a new >>>T=("Rama","Heena","Raj",
sorted list (does not sort the tuple itself). "Mohsin","Aditya")
>>> sorted(T)
['Aditya', 'Heena',
'Mohsin', 'Raj', 'Rama']
min() Returns minimum element of the tuple >>> T=(19,12,56,18,9,87,34)
max() Returns maximum element of the tuple >>> min(T)
sum() Returns sum of the elements of the tuple. 9
>>> max(T)
87
>>> sum(T)
235
TUPLE ASSIGNMENT
Assignment of tuple is a very useful feature in Python.
It allows variables of type tuple on the left side of the assignment operator to be
assigned respective values from variables of tuple on the right side.
If there is an expression on the right side then first that expression is evaluated and
then the result is assigned to the tuple.

For Example:
>>> (num1,num2) = (10,20)
>>> print(num1)
10
>>> print(num2)
20

>>> (num3,num4) = (10+5,20+5)


>>> print(num3)
15
>>> print(num4)
25
NESTED TUPLES
A tuple inside another tuple is called nested tuple.
In the example below roll number, name and marks (in percentage) of students are
saved in a tuple. To store details of many such students we can create a nested
tuple.

#To store records of students in tuple and print them


st=((101,"Aman",98),(102,"Geet",95),(103,"Sahil",87),(104,"Pawan",79))
print("S_No"," Roll_No"," Name"," Marks")
for i in range(0,len(st)):
print((i+1),'\t',st[i][0],'\t',st[i][1],'\t',st[i][2])

OUTPUT:
S_No Roll_No Name Marks
1 101 Aman 98
2 102 Geet 95
3 103 Sahil 87
4 104 Pawan 79
LIST VS TUPLE
✔Lists and Tuples both are sequences and can have elements of any type

✔Both lists and tuples maintain the order of the elements (unlike dictionaries and
sets).

✔We generally use lists to store elements of the same data type and tuples to store
elements of different data types.

✔The main difference between lists and tuples is that lists are mutable sequences
(can be changed) and tuples are immutable sequences (cannot be changed). Lists
can grow or shrink while tuples cannot.

✔If we have data that does not change then storing this data in a tuple will make sure
that it is not changed accidentally.

✔As we know tuples are immutable, iterating through tuple is faster as compare to
lists.
Q1. Write a program to swap two numbers without using a
temporary variable.

#Program to swap two numbers


num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print("\n\nNumbers before swapping:")
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1) #Tuple assignment
print("\n\nNumbers after swapping:")
print("First Number:",num1)
print("Second Number:",num2)
Q2. Write a function to compute area and circumference of a circle
and return these two values from the function.

#Function to compute area and circumference of the circle.


def circle(r):
area = 3.14*r*r
circumference = 2*3.14*r
return (area, circumference) #returning a tuple
#end of function

Radius = int(input('Enter radius of circle'))


Area, circumference = circle(radius) #unpacking a tuple
print('Area of circle is: ',area)
print('Circumference of circle is: ',circumference)
Q3. Write a program to input n numbers from the user and store
these numbers in the tuple. Print the maximum and minimum
number from this tuple.

numbers = tuple() #create an empty tuple


n = int(input("How many numbers you want to enter?"))
for i in range(0,n):
num = int(input())
numbers = numbers +(num,) #every time a new tuple is created
print('\n\nThe numbers in the tuple are:')
print(numbers)
print("\n The maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
>>>(2) #parenthesized expression

>>>(2,) # singleton tuple

>>>2, 4, 6 #another notation


(2, 4, 6)
Q4. Consider a tuple t1={1,2,5,7,9,2,4,6,8,10}.
WAP to perform following operations:

Print another tupple whose values are even number in the given tuple.
Concatenate tuple t2={11,13,15} with t1.
Return maximum and minimum value from this tuple.

◆ STEPS-

Firstly we will create a for loop which will check whether a element in
tuple is even or not by using (i%2==0) condition and then place them in
another tuple.
Then we will use + operator for concatenating following tuples.
And for finding minimum and maximum element in t1 tuple we will use
min() and max() built in functions.
CODE :-
OUTPUT :-
DRY RUN

Value of i i%2 OUTPUT


(t1 elements)
When i=1 1%2==1 As reminder is not 0
Elemnet will be skipped
and loop continues.

When i=2 2%2==0 Element will be


appended in tuple tp.
As it is even.(Rim==0)
When i=7 7%2==1 As reminder is not 0
Elemnet will bw skipped
and loop continues.
Q5. Consider a tuple t1={1,2,5,7,9,2,4,6,8,10}.
Write a program to perform following operations:
a) Print half the values of tuple in one line and the other half in the next line.
b) Print another tuple whose values are even numbers in the given tuple.
c) Concatenate a tuple t2={11,13,15) with t1.
d) Return maximum and minimum value from this tuple.

t1=(1,2,5,7,9,2,4,6,8,10)
s=len(t1)
mid=int(s/2)
print(t1[0:mid])
print(t1[mid:])
empty_tuple=()
i=0
while(i<s):
if(t1[i]%2==0):
empty_tuple+=(t1[i],)
i=i+1
print("new tuple with even elements\n",empty_tuple)

t2=(11,13,15)
print("adding t1 and t2=",t1+t2)
print("largest element in t1 is:",max(t1))
print("smallest element in t1 is:",min(t1))
The tuple t is defined as:
t = ("Ram","Shyam",[40,38])

Give the output/ indicate error in each of the following code snippets:

i) t[1] = "Lakhan" print(t)


ii) t[2][0] = 45 print(t)

Ans:
(i) Tuples are unchangeable or immutable so to change values inside we need to convert it
to a list then change the values then again change it back to tuple.
(ii) On the other hand, mutable objects stored in a tuple do not lose their mutability e.g.
you can still modify inner lists.
Code: output:
Q6. Write a function that takes the lengths of three sides:
side1, side2 and side3 of the triangle
as the input from the user using input function and
return the area and perimeter of the triangle as a tuple.
Also, assert that
sum of the length of any two sides is greater than the third side.

Q7. Write a program to accept age of n students form the user.


Store them in tuple “Age”. Now call a function which accepts “Age” tuple
as parameter and returns a tuple “SortedAge” which has age of students in
the ascending order. Write another function which accepts “SortedAge”
tuple
as parameter and returns number of students which have age =18.
Q8. Consider a tuple names defined as follows:

names = ("Ram", "Shyam")

Write a statement using a single operator that creates another tuple namesX
that adds the name "Lakhan" to the tuple names.

You might also like