Python Programming Language
TUPLE
Learning Outcome
To introduce Tuple data type in Python
programming language.
To be able to code utilising the Tuple.
Introduction
Used to keep multiple items in a single
variable.
It is collection of ordered and unchangeable
items.
Can include duplicate values.
Written with round brackets.
It is indexed with first item as index (0),
second item with index (1) and so on…
Sample
studentList = (“Ahmad”, “Lim”, “Sara”)
print(studentList)
Sample 2 – One Item
studentList = (“Ahmad”)
studentList = (“Ahmad”,) print(type(studentList))
print(studentList)
Sample 3 – Allow duplicate
studentList = (“Ahmad”, “Lim”, “Sara”, “Lim”)
print(studentList)
Len
studentList = (“Ahmad”, “Lim”, “Sara”)
print(len(studentList))
Sample 2 – Any data type
studentList = (“Feroz”, 44, True, “Male”)
Access Tuple
studentList = (“Ahmad”, “Lim”, “Sara”)
print(studentList[1])
Recalled?: The first item is index[0]
NEW: -1 is referring to the last
item, -2 is second last item.
Access Tuple 2
myFruitsItems = (“Rambutan”, “Mangosteen”,
“Langsat”, “Mango”, “Ciku”, “Banana”)
print(myFruitsItems[2:5])
NOTE: start from index 2 BUT not included index 5
Change Tuple Value
Please remember Tuple is unchangeable, OR add new item OR
remove an item once it was created.
BUT, we can convert it to list and reconvert it to Tuple.
myFruitsItems = (“Rambutan”, “Mangosteen”, “Langsat”,
“Mango”, “Ciku”, “Banana”)
temp = list(myFruitsItems)
temp[3] = “Cempedak”
myFruitsItems = tuple(temp)
print(myFruitsItems)
Loop Tuple
myFruitsItems = (“Rambutan”, “Mangosteen”,
“Langsat”, “Mango”, “Ciku”, “Banana”)
for z in range(len(myFruitsItems)):
print(myFruitsItems[z])
Tutorial
Assign the following string to Tuple and display
“ROG”
P R O G R A M