PYTHON TUPLES
Creating a Tuples
• INPUT :
tup = () # Creating an empty Tuple
print(tup)
tup = ('Geeks', 'For') # Using String
print(tup)
li = [1, 2, 4, 5, 6] # Using List
print(tuple(li))
tup = tuple('Geeks') # Using Built-in Function
print(tup)
• OUTPUT :
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
('G', 'e', 'e', 'k', 's')
Creating a Tuple with Mixed Datatypes
• INPUT :
tup = (5, 'Welcome', 7, 'Geeks') # Creating a Tuple with Mixed Datatype
print(tup)
tup1 = (0, 1, 2, 3) # Creating a Tuple with nested tuples
tup2 = ('python', 'geek')
tup3 = (tup1, tup2)
print(tup3)
tup1 = ('Geeks',) * 3 # Creating a Tuple with repetition
print(tup1)
tup = ('Geeks') # Creating a Tuple with the use of loop
n=5
for i in range(int(n)):
tup = (tup,)
print(tup)
• OUTPUT :
(5, 'Welcome', 7, 'Geeks')
((0, 1, 2, 3), ('python', 'geek'))
('Geeks', 'Geeks', 'Geeks')
('Geeks',)
(('Geeks',),)
((('Geeks',),),)
(((('Geeks',),),),)
((((('Geeks',),),),),)
Accessing of Tuples
• INPUT :
tup = tuple("Geeks") # Accessing Tuple with Indexing
print(tup[0])
print(tup[1:4]) # Accessing a range of elements using slicing
print(tup[:3])
tup = ("Geeks", "For", "Geeks") # Tuple unpacking
a, b, c = tup # This line unpack values of Tuple1
print(a)
print(b)
print(c)
• OUTPUT :
G
('e', 'e', 'k')
('G', 'e', 'e')
Geeks
For
Geeks
Concatenation of Tuples
• INPUT :
tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')
tup3 = tup1 + tup2
print(tup3)
• OUTPUT :
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')
Slicing of Tuple
• INPUT :
tup = tuple('GEEKSFORGEEKS') # Slicing of a Tuple with Numbers
print(tup[1:]) # Removing First element
print(tup[::-1]) # Reversing the Tuple
print(tup[4:9]) # Printing elements of a Range
• OUTPUT :
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
('S', 'F', 'O', 'R', 'G')
Deleting a Tuple
• INPUT :
tup = (0, 1, 2, 3, 4) # Deleting a Tuple
del tup
print(tup)
• OUTPUT :
ERROR!
Traceback (most recent call last):
File "<[Link]>", line 6, in <module>
NameError: name 'tup' is not defined