A tuple in Python is an ordered collection of items that is immutable, meaning it cannot be changed after creation. Tuples are written using round brackets () and are often used for data that should stay constant.
Tuples are usually defined with parentheses (), with items separated by commas:
my_tuple = ("apple", "banana", "cherry")
Python also allows creating tuples without parentheses when there is no ambiguity: my_tuple = "apple", "banana", "cherry". Internally, it is still a tuple.
This example creates a simple tuple of fruits and prints it.
my_tuple = ("apple", "banana", "cherry")
print(my_tuple)
You can access tuple items using indexing. Indexing starts at 0 from the left, and negative indices start from -1 from the right.
my_tuple = ("apple", "banana", "cherry")
print(my_tuple[0]) # apple
print(my_tuple[-1]) # cherry
Use the len() function to get the number of items in a tuple.
my_tuple = ("apple", "banana", "cherry")
print(len(my_tuple))
To create a tuple with only one item, you must include a trailing comma. Without it, Python treats the value as a normal variable (like a string), not a tuple.
single_tuple = ("apple",)
print(type(single_tuple)) # <class 'tuple'>
not_a_tuple = ("apple")
print(type(not_a_tuple)) # <class 'str'>
Tuples can store values of different data types in a single collection.
mixed_tuple = ("abc", 34, True, 40.5)
print(mixed_tuple)
print(my_tuple) → prints the entire tuple, e.g. ("apple", "banana", "cherry").print(my_tuple[0]) → prints the first item: apple.print(my_tuple[-1]) → prints the last item: cherry.print(len(my_tuple)) → prints the number of items, here 3.type(single_tuple) → <class 'tuple'>type(not_a_tuple) → <class 'str'>print(mixed_tuple) → prints all the mixed values as a tuple, e.g. ("abc", 34, True, 40.5).(x, y), dates, etc.("apple",).[]) when you need to frequently add, remove, or update items.() can be optional when defining tuples, but using them improves readability.len().type().TypeError that occurs.