A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable.
('python', 'geeks') ('python', 'geeks')
Note: In case your generating a tuple with a single element, make sure to add a comma after the element.
Concatenation of Tuples
(0, 1, 2, 3, 'python', 'geek')
Nesting of Tuples
((0, 1, 2, 3), ('python', 'geek'))
Repetition in Tuples
('python', 'python', 'python')
Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’.
Traceback (most recent call last): File "e0eaddff843a8695575daec34506f126.py", line 3, in tuple1=4 TypeError: 'tuple' object does not support item assignment
Slicing in Tuples
(1, 2, 3) (3, 2, 1, 0) (2, 3)
Deleting a Tuple
Traceback (most recent call last): File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module> print(tuple3) NameError: name 'tuple3' is not defined
Finding Length of a Tuple
Converting list to a Tuple
(0, 1, 2) ('p', 'y', 't', 'h', 'o', 'n')
Takes a single parameter which may be a list,string,set or even a dictionary( only keys are taken as elements) and converts them to a tuple.
Tuples in a loop
(('geek',),) ((('geek',),),) (((('geek',),),),) ((((('geek',),),),),) (((((('geek',),),),),),)
Using cmp(), max() , min()
Not the same Maximum element in tuples 1,2: python,coder Minimum element in tuples 1,2: geek,1
Note: max() and min() checks the based on ASCII values. If there are two strings in a tuple, then the first different character in the strings are checked.
This article is contributed by Sri Sanketh Uppalapati. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course