0% found this document useful (0 votes)
20 views48 pages

Tuples Online

A tuple is an immutable ordered sequence of elements that can contain different data types and is defined using parentheses. Elements can be accessed via indexing and slicing, and tuples support operations like concatenation, repetition, and membership testing. Various built-in functions and methods, such as len(), count(), and index(), can be used to manipulate and retrieve information from tuples.

Uploaded by

Ishaan Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views48 pages

Tuples Online

A tuple is an immutable ordered sequence of elements that can contain different data types and is defined using parentheses. Elements can be accessed via indexing and slicing, and tuples support operations like concatenation, repetition, and membership testing. Various built-in functions and methods, such as len(), count(), and index(), can be used to manipulate and retrieve information from tuples.

Uploaded by

Ishaan Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

(tuples,)

immutable
A tuple is an ordered sequence of elements of different data types, such as integer, float,
string, list or even a tuple.
Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by
commas.
Like list and string, elements of a tuple can be accessed using index values, starting from
0.

#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)

#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))
• If there is only a single element in a tuple then the element should be followed by a
comma.

#incorrect way of assigning single element to #tuple


#tuple5 is assigned a single element
>>> tuple5 = (20)
>>> tuple5
20
>>>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'>
#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)
>>>seq=5
>>>type(seq) #seq is an integer
>>>seq=5, #seq is a tuple
>>>seq=(5) #seq is an integer
>>>seq=(5,) #seq is a tuple
Accessing Elements in a Tuple
Elements of a tuple can be accessed in the same way as a list or string using
indexing and slicing. Index 0 1 2 3 4 5
>>> tuple1 = (2,4,6,8,10,12) Element→ 2 4 6 8 10 12

#returns the first element of tuple1


>>> tuple1[0]
2
#returns fourth element of tuple1
>>> tuple1[3]
8
#returns error as index is out of range
>>> tuple1[15]
IndexError: tuple index out of range
#an expression resulting in an integer index
Accessing Elements in a Tuple
Elements of a tuple can be accessed in the same way as a list or string using
indexing and slicing. Index 0 1 2 3 4 5
>>> tuple1 = (2,4,6,8,10,12) Element→ 2 4 6 8 10 12

>>> tuple1[1+4]
12

#returns first element from right


>>> tuple1[-1]
12
Tuple is Immutable
Tuple is an immutable data type. It means that the elements of a 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., a list.
#4th element of the tuple2 is a list
>>> tuple2 = (1,2,3,[8,9])
#modify the list element of the tuple tuple2
>>> tuple2[3][1] = 10
#modification is reflected in tuple2
>>> tuple2
(1, 2, 3, [8, 10])
Tuple
Operations
Concatenation
Python allows us to join tuples using concatenation operator depicted by symbol +.
>>> 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 stores elements of tuple3 and tuple4
>>> tuple5 = tuple3 + tuple4
>>> tuple5
('Red','Green','Blue','Cyan','Magenta’,
'Yellow','Black')
Concatenation operator can also be used for extending an existing
tuple. When we extend a tuple using concatenation a new tuple is
created.
>>> tuple6 = (1,2,3,4,5)
#single element is appended to tuple6
>>> tuple6 = tuple6 + (6,)
>>> tuple6
(1, 2, 3, 4, 5, 6)
#more than one elements are appended
>>> tuple6 = tuple6 + (7,8,9)
>>> tuple6
(1, 2, 3, 4, 5, 6, 7, 8, 9)
Note: everytime tuple would be at different id
Repetition
Repetition operation is depicted by the symbol *. It is used to repeat elements of
a tuple. We can repeat the tuple elements. The repetition operator requires the
one operand to be a tuple and the other operand to be an integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello',
'World')
#tuple with single element
>>> tuple2 = ("Hello",)
>>> tuple2 * 4
('Hello', 'Hello', 'Hello', 'Hello')
Membership
The in operator checks if the element is present in the tuple and
returns True, else it 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
Slicing
Like string and list, slicing can be applied to tuples also.
0 1 2 3 4 5 6 7
>>> tuple1 = (10,20,30,40,50,60,70,80)
#elements from index 2 to index 6
>>> tuple1[2:7]
(30, 40, 50, 60, 70)
#all elements of tuple are printed
>>> tuple1[0:len(tuple1)]
(10, 20, 30, 40, 50, 60, 70, 80)
#slice starts from zero index
>>> tuple1[:5]
(10, 20, 30, 40, 50)
#slice is till end of the tuple
>>> tuple1[2:]
(30, 40, 50, 60, 70, 80)
Slicing
Like string and list, slicing can be applied to tuples also.
0 1 2 3 4 5 6 7
>>> tuple1 = (10,20,30,40,50,60,70,80)
#step size 2 -8 -7 -6 -5 -4 -3 -2 -1

>>> tuple1[0:len(tuple1):2]
(10, 30, 50, 70)
#negative indexing
>>> tuple1[-6:-4]
(30, 40)
#tuple is traversed in reverse order
>>> tuple1[::-1]
(80, 70, 60, 50, 40, 30, 20, 10)
Tuple Methods
and
Built-in Functions
len()

Returns the length or the number of elements of the tuple


passed as the argument

>>> tuple1 = (10,20,30,40,50)


>>> len(tuple1)
5
tuple()

Creates an empty tuple if no argument is passed


>>> tuple1 = tuple()
>>> tuple1
( )

Creates a tuple if a sequence is passed as argument


>>> tuple1 = tuple('aeiou’) #string
>>> tuple1
('a', 'e', 'i', 'o', 'u')
>>> tuple2 = tuple([1,2,3]) #list
>>> tuple2
(1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)
count() Returns the number of times the given element appears
in the tuple

>>> tuple1 = (10,20,30,10,40,10,50)


>>> tuple1.count(10)
3
>> tuple1.count(90)
0
index(): Returns the index of the first occurrence of the
element in the given tuple

>>> tuple1 = (10,20,30,40,50)


>>> tuple1.index(30)
2

>>> tuple1.index(90)
ValueError: tuple.index(x): x not in
tuple
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=("Rama","Heena","Raj","Mohsin","Aditya
")
>>> sorted(tuple1)
['Aditya', 'Heena', 'Mohsin', 'Raj',
'Rama']
min()
Returns minimum or smallest element of the tuple
max()
Returns maximum or largest element of the tuple
sum()
Returns sum of the elements of the tuple
>>> tuple1 = (19,12,56,18,9,87,34)
>>> min(tuple1)
9
>>> max(tuple1)
87
>>> sum(tuple1)
235
Tuple Assignment
• Assignment of tuple is a useful feature in Python.
• It allows a tuple of variables on the left side of the
assignment operator to be assigned respective values
from a tuple on the right side.
• The number of variables on the left should be same as the
number of elements in the tuple.
Tuple Assignment
##The first element 10 is assigned to num1 and the
second element 20 is assigned to num2.
>>> (num1,num2) = (10,20)
>>> print(num1)
10
>>> print(num2)
20
>>> record = ( "Pooja",40,"CS")#packing
>>> (name,rollNo,subject) = record #unpacking
>>> name
'Pooja' >>> (a,b,c,d) = (5,6,8)
>>> rollNo ValueError: not enough
40 values to unpack
>>> subject (expected 4, got 3)
'CS'
Tuple Assignment
If there is an expression on the right side then first that expression is evaluated
and finally the result is assigned to the tuple.

#25 is assigned to num4


>>> (num3,num4) = (10+5,20+5)
>>> print(num3)
15
>>> print(num4)
25
Nested Tuples
A tuple inside another tuple is called a nested tuple. In the program 10-1, 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.
Program 10-1 This is a program to create a nested tuple to store roll number, name and marks
of students
#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
Tuple Handling
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("\nNumbers before swapping:")
print("First Number:",num1)
print("Second Number:",num2) Output:
Enter the first number: 5
(num1,num2) = (num2,num1) Enter the second number: 10
print("\nNumbers after swapping:") Numbers before swapping:
First Number: 5
print("First Number:",num1) Second Number: 10
print("Second Number:",num2) Numbers after swapping:
First Number: 10
Second Number: 5
Write a program to compute the area and circumference of a circle using a function.
Function should return area and circumference
#Function to compute area and circumference of the circle.
def circle(r):
area = 3.14*r*r
circumference = 2*3.14*r
#returns a tuple having two elements area and circumference
return (area,circumference)

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


area,circumference = circle(radius)
print('Area of circle is:',area)
print('Circumference of circle is:',circumference)
Output:
Enter radius of circle: 5
Area of circle is: 78.5
Circumference of circle is: 31.400000000000002
Write a program to input n numbers from the user. Store these numbers in a
tuple. Print the maximum and minimum 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())
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
Output:
print(numbers) How many numbers do you want to enter?:
5
print("\nThe maximum number is:") 98
10
print(max(numbers)) 12
15
print("The minimum number is:") The numbers in the tuple are:
(9, 8, 10, 12, 15)
print(min(numbers)) The maximum number is:
15
The minimum number is:
8
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45))
ii. print(tuple1.count(45))
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print(sorted(tuple1))
print(tuple1)
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45)) #2
ii. print(tuple1.count(45))
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print(sorted(tuple1))
print(tuple1)
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45)) #2
ii. print(tuple1.count(45)) #3
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print(sorted(tuple1))
print(tuple1)
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45)) #2
ii. print(tuple1.count(45)) #3
iii. print(tuple1 + tuple2) #(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv. print(len(tuple2))
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print(sorted(tuple1))
print(tuple1)
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45)) #2
ii. print(tuple1.count(45)) #3
iii. print(tuple1 + tuple2) #(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv. print(len(tuple2)) #2
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print(sorted(tuple1))
print(tuple1)
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45)) #2
ii. print(tuple1.count(45)) #3
iii. print(tuple1 + tuple2) #(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv. print(len(tuple2)) #2
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print(sorted(tuple1))
print(tuple1)
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45)) #2
ii. print(tuple1.count(45)) #3
iii. print(tuple1 + tuple2) #(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv. print(len(tuple2)) #2
v. print(max(tuple1)) #67
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print(sorted(tuple1))
print(tuple1)
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45)) #2
ii. print(tuple1.count(45)) #3
iii. print(tuple1 + tuple2) #(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv. print(len(tuple2)) #2
v. print(max(tuple1)) #67
vi print(min(tuple1)) #1
vii. print(sum(tuple2)) #300
viii. print(sorted(tuple1))
print(tuple1)
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45)) #2
ii. print(tuple1.count(45)) #3
iii. print(tuple1 + tuple2) #(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv. print(len(tuple2)) #2
v. print(max(tuple1)) #67
vi print(min(tuple1)) #1
vii. print(sum(tuple2)) #300
viii. print(sorted(tuple1)) #[1, 9, 23, 45, 45, 45, 55, 67]
print(tuple1) # (23, 1, 45, 67, 45, 9, 55, 45)
A tuple t1 stores (11,21,31,42,51), where its second last element is
mistyped. Write a program to correct its second last element as 41.

================== RESTART: C:/python37/class 11/tuple/1.py ==================


modified tuple: (11, 21, 31, 41, 51)
A tuple t1 stores (11,21,31,42,51), where its second last element is
mistyped. Write a program to correct its second last element as 41.

t=(11,21,31,42,51)
t1=list(t)
t1[-2]=41
t=tuple(t1)
print("modified tuple:",t)
Given a tuple T(1,2,”a”,”b”). There is a list L with some elements. Replace first
four elements of list with all four elements of the tuple in single statement.
Print the list before and after the list is modified.
================== RESTART: C:/python37/class 11/tuple/2.py
==================
List before unpacking:
['hello', 'there', 'are', 'some', 'numbers', 'coming', 'from', 'tuples']
List after unpacking:
[1, 2, 'a', 'b', 'numbers', 'coming', 'from', 'tuples']
>>>
Given a tuple T(1,2,”a”,”b”). There is a list L with some elements. Replace first
four elements of list with all four elements of the tuple in single statement.
Print the list before and after the list is modified.
t=(1,2,"a","b")
l=["hello","there","are","some","numbers","coming","from","tuples"]
print("List before unpacking:")
print(l)
l[0],l[1],l[2],l[3]=t
print("List after unpacking:")
print(l)
Tuples are immutable. t=([11,12],[14,15,16])
The following code gives no error when executed. Why? print(t)
Predict the output t[0].append(13)
pritn(t)
Tuples are immutable. t=([11,12],[14,15,16])
The following code gives no error when executed. Why? print(t)
Predict the output t[0].append(13)
print(t)

The mutable elements can always change, thus line 3 of the code
is actually modifying the list without modifying its memory
address
OUTPUT
([11,12],[14,15,16])
([11,12,13],[14,15,16])
WAP to check if a tuple contains any duplicate element

================== RESTART: C:/python37/class 11/tuple/3.py ==================


Enter tuple(6,7,1,12,13,1,7)
tuple contains duplicate elements
>>>
================== RESTART: C:/python37/class 11/tuple/3.py ==================
Enter tuple(1,2,3,4)
>>>
WAP to check if a tuple contains any duplicate element
================== RESTART: C:/python37/class 11/tuple/3.py ==================
Enter tuple(6,7,1,12,13,1,7)
tuple contains duplicate elements
>>>
================== RESTART: C:/python37/class 11/tuple/3.py ==================
Enter tuple(1,2,3,4)
>>>

t=eval(input("Enter tuple"))
for ele in t:
if t.count(ele)>1:
print("tuple contains duplicate elements")
break
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy