SlideShare ist ein Scribd-Unternehmen logo
1 von 22
PRESENTATION ON TUPLES
INTRODUCTION
• 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.
• For example. #tuple1 is the tuple of integers
>>> tuple1 = (1,2,3,4,5)
>>> tuple1 (1, 2, 3, 4, 5)
• 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
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.
• >>> tuple1 = (2,4,6,8,10,12)
#initializes a tuple tuple1
#returns the first element of tuple1
>>> tuple1[0]
IMMUTABILITY
• 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)
Difference Between Tuple and List
• List is mutable but tuple is immutable. So iterating through a tuple
is faster as compared to a list. √ If we have data that does not
change then storing this data in a tuple will make sure that it is
not changed accidentally.
OPERATORS IN TUPLE
• CONCATENATION: Python allows us to join tuples using
concatenation operator depicted by symbol +. We
can also create a new tuple which contains the result of this
concatenation operation.
>>> 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) Concatenation
operator can also be used for extending an existing tuple. When we
extend a tuple using concatenation a new tuple is created.
• REPETITON: 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 first operand to be
a tuple and the second operand to be an integer only.
>>> tuple1 = ('Hello','World’)
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
• SLICING: Like string and list, slicing can be applied to tuples
also.
#tuple1 is a tuple
>>> tuple1 = (10,20,30,40,50,60,70,80)
#elements from index 2 to index 6
>>> tuple1[2:7]
(30, 40, 50, 60, 70)
• FUNCTION: 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
• Creates a tuple if a sequence is passed as argument
>>> tuple1 = tuple()
>>> tuple1 ( )
>>> 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
CONTD.
(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)
NESTED TUPLES
A tuple inside another tuple is called a nested tuple.
>>>t1 = ((“Amit”, 90), (“Sumit”, 75), (“Ravi”, 80))
>>>t1[0] (‘Amit’, 90)
>>>t1[1] (‘Sumit’, 75)
>>>t1[1][1] 75
TUPLE ASSIGNMENT
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. For Example
>>>(n1,n2) = (5,9)
>>>print(n1)
5
print(n2)
9
>>>(a,b,c,d) = (5,6,8) #values on left side and right side are not equal
ValueError: not enough values to unpack
QNA
Q1.Write a program that interactively create a nested
tuple to store the marks in three subjects for five
student .
Ans. total = ()
for i in range(3):
mark = () mark1 = int(input("enter the marks of first subject = "))
mark2 = int(input("enter the marks of second subject = "))
mark3 = int(input("enter the marks of third subject = "))
mark = (mark1 , mark2 , mark3)
total= total + (mark)
print("total marks = ",total)
Q2.Write a program to create a nested tuple to store
roll number, name and marks of student
Ans. tup= ()
while True :
roll = int(input("Enter a roll number :- "))
name = input("Enter name :-")
mark = input("Enter marks :-")
tup += ( (roll,name,mark ),)
user = input("Do you want to quit enter yes =")
if user == "yes":
print(tup)
break
Q3.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:
1.print(tuple1.index(45))
Ans. The 'index()' function returns the index of the first occurrence of the element in a tuple. 2
2.print(tuple1.count(45))
Ans. The 'count()' function returns the numbers of times the given element appears in the tuple. 3
3.print(tuple1 + tuple2)
Ans. '+' operator concatenate the two tuples. (23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
4.print(len(tuple2))
Ans. The 'len()' function returns the number of elements in the given tuple. 2
5.print(max(tuple1))
Ans. The 'max()' function returns the largest element of the tuple. 67
6.print(min(tuple1))
Ans. The 'min()' function returns the smallest element of the tuple. 1
7.print(sum(tuple2))
Ans. The 'sum()' function returns the sum of all the elements of the tuple. 300
8.print(sorted (tuple1)) print(tuple1)
Ans. The 'sorted()' function takes element in the tuple and return a new sorted list. It doesn’t make any
changes to the original tuple. Hence, print(tuple1) will print the original tuple1 i.e. (23, 1, 45, 67, 45, 9, 55,
45) . [1, 9, 23, 45, 45, 45, 55, 67] (23, 1, 45, 67, 45, 9, 55, 45)
Q4.Carefully read the given code fragments and
figure out the errors that the code may produce.
• (a)
t = ('a', 'b', 'c', 'd', 'e’)
print(t[5])
Ans. IndexError: tuple index out of range
• (b)
t = ('a', 'b', 'c', 'd', 'e’)
t[0] = ‘A’
Ans. TypeError: 'tuple' object does not support item assignment
• (c)
t1 = (3)
t2 = (4, 5, 6)
t3 = t1 + t2
print(t3)
Ans. TypeError: unsupported operand type(s) for +: 'int' and 'tuple’
• (d)
t2 = (4, 5, 6)
t3 = (6, 7)
print(t3 - t2)
Ans. TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'
• (e)
t3 = (6, 7)
t4 = t3 * 3
t5 = t3 * (3)
t6 = t3 * (3,)
print(t4)
print(t5)
print(16)
Ans. TypeError: can't multiply sequence by non-int of type 'tuple’
• (f)
t = ('a', 'b', 'c', 'd', 'e’)
1, 2, 3, 4, 5, = t
Ans. Syntax error
• (g)
2t = ('a', 'b', 'c, d', 'e’)
1n, 2n, 3n, 4n, 5n = t
Ans. Invalid syntax
• (h)
t = ('a', 'b', 'c', 'd', 'e’)
x, y, z, a, b = t
Ans. No Error
• (i) t = ('a', 'b', 'c', 'd', 'e’)
a, b, c, d, e, f = t
Ans. ValueError : not enough values to unpack (expected 6, got 5)
Q5. What does each of the following expressions
evaluate to? Suppose that T is the tuple ("These",
("are", "a", "few", "words"), "that", "we", "will", "use")
• (a) T[1][0: : 2]
Ans. ('are', 'few')
• (b) "a" in T [1] [ 0 ]
Ans. True
• (c) T [ : 1 ] + T[ 1 ]
Ans. ('These', 'are', 'a', 'few', 'words')
• (d) T[ 2 : : 2 ]
Ans. ('that', 'will')
• (e) T[2][2] in T[1]
Ans. True
THANK YOU

Weitere ähnliche Inhalte

Was ist angesagt?

02 JavaScript Syntax
02 JavaScript Syntax02 JavaScript Syntax
02 JavaScript Syntax
Ynon Perek
 

Was ist angesagt? (20)

Enums in c
Enums in cEnums in c
Enums in c
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 
Python collections
Python collectionsPython collections
Python collections
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
4. listbox
4. listbox4. listbox
4. listbox
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Css Ppt
Css PptCss Ppt
Css Ppt
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
02 JavaScript Syntax
02 JavaScript Syntax02 JavaScript Syntax
02 JavaScript Syntax
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data Analysis
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
 
Html tables, forms and audio video
Html tables, forms and audio videoHtml tables, forms and audio video
Html tables, forms and audio video
 
Array in C
Array in CArray in C
Array in C
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 

Ähnlich wie PRESENTATION ON TUPLES.pptx

Ähnlich wie PRESENTATION ON TUPLES.pptx (20)

Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptxTuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
updated_tuple_in_python.pdf
updated_tuple_in_python.pdfupdated_tuple_in_python.pdf
updated_tuple_in_python.pdf
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python Tuple.pdf
Python Tuple.pdfPython Tuple.pdf
Python Tuple.pdf
 
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptxLecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
Python programming for Beginners - II
Python programming for Beginners - IIPython programming for Beginners - II
Python programming for Beginners - II
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptx1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptx
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Effective tuples in phyton template.pptx
Effective tuples in phyton template.pptxEffective tuples in phyton template.pptx
Effective tuples in phyton template.pptx
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
Tuple.py
Tuple.pyTuple.py
Tuple.py
 

Kürzlich hochgeladen

Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 

Kürzlich hochgeladen (20)

Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 

PRESENTATION ON TUPLES.pptx

  • 2. INTRODUCTION • 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. • For example. #tuple1 is the tuple of integers >>> tuple1 = (1,2,3,4,5) >>> tuple1 (1, 2, 3, 4, 5) • 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
  • 3. 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. • >>> tuple1 = (2,4,6,8,10,12) #initializes a tuple tuple1 #returns the first element of tuple1 >>> tuple1[0]
  • 4. IMMUTABILITY • 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) Difference Between Tuple and List • List is mutable but tuple is immutable. So iterating through a tuple is faster as compared to a list. √ If we have data that does not change then storing this data in a tuple will make sure that it is not changed accidentally.
  • 5. OPERATORS IN TUPLE • CONCATENATION: Python allows us to join tuples using concatenation operator depicted by symbol +. We can also create a new tuple which contains the result of this concatenation operation. >>> 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) Concatenation operator can also be used for extending an existing tuple. When we extend a tuple using concatenation a new tuple is created.
  • 6. • REPETITON: 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 first operand to be a tuple and the second operand to be an integer only. >>> tuple1 = ('Hello','World’) >>> tuple1 * 3 ('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
  • 7. • SLICING: Like string and list, slicing can be applied to tuples also. #tuple1 is a tuple >>> tuple1 = (10,20,30,40,50,60,70,80) #elements from index 2 to index 6 >>> tuple1[2:7] (30, 40, 50, 60, 70)
  • 8. • FUNCTION: 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 • Creates a tuple if a sequence is passed as argument >>> tuple1 = tuple() >>> tuple1 ( ) >>> 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
  • 9. CONTD. (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)
  • 10. • 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)
  • 11. NESTED TUPLES A tuple inside another tuple is called a nested tuple. >>>t1 = ((“Amit”, 90), (“Sumit”, 75), (“Ravi”, 80)) >>>t1[0] (‘Amit’, 90) >>>t1[1] (‘Sumit’, 75) >>>t1[1][1] 75
  • 12. TUPLE ASSIGNMENT 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. For Example >>>(n1,n2) = (5,9) >>>print(n1) 5 print(n2) 9 >>>(a,b,c,d) = (5,6,8) #values on left side and right side are not equal ValueError: not enough values to unpack
  • 13. QNA Q1.Write a program that interactively create a nested tuple to store the marks in three subjects for five student . Ans. total = () for i in range(3): mark = () mark1 = int(input("enter the marks of first subject = ")) mark2 = int(input("enter the marks of second subject = ")) mark3 = int(input("enter the marks of third subject = ")) mark = (mark1 , mark2 , mark3) total= total + (mark) print("total marks = ",total)
  • 14. Q2.Write a program to create a nested tuple to store roll number, name and marks of student Ans. tup= () while True : roll = int(input("Enter a roll number :- ")) name = input("Enter name :-") mark = input("Enter marks :-") tup += ( (roll,name,mark ),) user = input("Do you want to quit enter yes =") if user == "yes": print(tup) break
  • 15. Q3.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: 1.print(tuple1.index(45)) Ans. The 'index()' function returns the index of the first occurrence of the element in a tuple. 2 2.print(tuple1.count(45)) Ans. The 'count()' function returns the numbers of times the given element appears in the tuple. 3 3.print(tuple1 + tuple2) Ans. '+' operator concatenate the two tuples. (23, 1, 45, 67, 45, 9, 55, 45, 100, 200) 4.print(len(tuple2)) Ans. The 'len()' function returns the number of elements in the given tuple. 2 5.print(max(tuple1)) Ans. The 'max()' function returns the largest element of the tuple. 67
  • 16. 6.print(min(tuple1)) Ans. The 'min()' function returns the smallest element of the tuple. 1 7.print(sum(tuple2)) Ans. The 'sum()' function returns the sum of all the elements of the tuple. 300 8.print(sorted (tuple1)) print(tuple1) Ans. The 'sorted()' function takes element in the tuple and return a new sorted list. It doesn’t make any changes to the original tuple. Hence, print(tuple1) will print the original tuple1 i.e. (23, 1, 45, 67, 45, 9, 55, 45) . [1, 9, 23, 45, 45, 45, 55, 67] (23, 1, 45, 67, 45, 9, 55, 45)
  • 17. Q4.Carefully read the given code fragments and figure out the errors that the code may produce. • (a) t = ('a', 'b', 'c', 'd', 'e’) print(t[5]) Ans. IndexError: tuple index out of range • (b) t = ('a', 'b', 'c', 'd', 'e’) t[0] = ‘A’ Ans. TypeError: 'tuple' object does not support item assignment
  • 18. • (c) t1 = (3) t2 = (4, 5, 6) t3 = t1 + t2 print(t3) Ans. TypeError: unsupported operand type(s) for +: 'int' and 'tuple’ • (d) t2 = (4, 5, 6) t3 = (6, 7) print(t3 - t2) Ans. TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'
  • 19. • (e) t3 = (6, 7) t4 = t3 * 3 t5 = t3 * (3) t6 = t3 * (3,) print(t4) print(t5) print(16) Ans. TypeError: can't multiply sequence by non-int of type 'tuple’ • (f) t = ('a', 'b', 'c', 'd', 'e’) 1, 2, 3, 4, 5, = t Ans. Syntax error
  • 20. • (g) 2t = ('a', 'b', 'c, d', 'e’) 1n, 2n, 3n, 4n, 5n = t Ans. Invalid syntax • (h) t = ('a', 'b', 'c', 'd', 'e’) x, y, z, a, b = t Ans. No Error • (i) t = ('a', 'b', 'c', 'd', 'e’) a, b, c, d, e, f = t Ans. ValueError : not enough values to unpack (expected 6, got 5)
  • 21. Q5. What does each of the following expressions evaluate to? Suppose that T is the tuple ("These", ("are", "a", "few", "words"), "that", "we", "will", "use") • (a) T[1][0: : 2] Ans. ('are', 'few') • (b) "a" in T [1] [ 0 ] Ans. True • (c) T [ : 1 ] + T[ 1 ] Ans. ('These', 'are', 'a', 'few', 'words') • (d) T[ 2 : : 2 ] Ans. ('that', 'will')
  • 22. • (e) T[2][2] in T[1] Ans. True THANK YOU