ALevel 1 Python 22apr SS
ALevel 1 Python 22apr SS
O Level / A Level
Tuple
Creating Tuple
tup1 = ( 'physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple.
thistuple = "apple", "mango"
print(type(thistuple))
thistuple = () Output
print(type(thistuple)) <class 'tuple'>
<class 'tuple'>
# a tuple with one item <class 'tuple'>
thistuple = ("apple",) <class 'str'>
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Access Items
To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index.
Output−
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
tup1[3]: 2000
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to
the second last item etc. tup1[-1]
Updating Tuple
Tuples are immutable which means we cannot update or change the values.
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)
Output
(12, 34.56, 'abc', 'xyz')
Adding new item in Tuple
t = (10, 20, 30, 40)
t = t + (60, ) # this will do modification of t.
print (t)
Output
(10, 20, 30, 40, 60)
Output
("apple", "kiwi", "cherry")
Tuple Length
To determine how many items a tuple has, use the len() function. e.g. print(len(tuple))
Built-in Function
Example
Write a program to input ‘n’ numbers and store it in tuple.
t=tuple()
n=input("Enter any number")