Python Tuples
A tuple is a set of data elements put in order using a comma and placed within brackets. They keep more than one item in a single variable. Tuples cannot be changed once they have been created.
Example:
colors =
("Red",
"Blue",
"White")
print(colors)
Output
("Red", "Blue", "White")
Access Tuple Items
You can retrieve elements of a tuple by using an index number.
Example:
colors =
("Red",
"Blue",
"white")
print(colors[1])
Output
Blue
Tuple Methods
Python provides two in-built methods to handle tuples.
count()
The count()
function returns the frequency with which the given items occur in the tuple.
Example:
colors =
("Red",
"Blue",
"White")
newtup = colors.count("White")
print(newtup)
Output:
1
index()
The index()
function returns the index of the first occurrence of the tuple element.
Example:
colors =
("Red",
"Blue",
"White")
newtup = colors.index("White")
print(newtup)
Output:
2