Python Basics
Python Tuples
Python tuples
Python Tuples
Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.
Create a Tuple
Tuples are created using round brackets:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Access Tuple Items
You can access tuple items by referring to the index number:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1]) # banana
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
Note: Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable.
Loop Through a Tuple
You can loop through the tuple items by using a for loop:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)