Tuples
Tuples
To determine how many items a tuple has, use the len() function:
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",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
© ISBAT UNIVERSITY – 2023. 01/06/2024
Tuple Items - Data Types
Example
String, int and boolean data types:
<class 'tuple'>
What is the data type?
You can access tuple items by referring to the index number, inside
square brackets:
-1 refers to the last item, -2 refers to the second last item etc.
This example returns the items from "cherry" and to the end:
Specify negative indexes if you want to start the search from the end
of the tuple:
print(x)
1. Convert into a list: Just like the workaround for changing a tuple,
you can convert it into a list, add your item(s), and convert it back
into a tuple.
print(thistuple)
add an * to the variable name and the values will be assigned to the
variable as a list:
You can loop through the tuple items by using a for loop.
Iterate through the items and print the values:
You can also loop through the tuple items by referring to their index
number.
Use the range() and len() functions to create a suitable iterable
Print all items by referring to their index number:
You can loop through the tuple items by using a while loop.
Use the len() function to determine the length of the tuple, then start
at 0 and loop your way through the tuple items by referring to their
indexes.
Remember to increase the index by 1 after each iteration.
count()
Returns the number of times a specified value occurs in a tuple
index()
Searches the tuple for a specified value and returns the position of