What are Python tuples?
Python tuples are immutable sequences of data. This means that the data in a tuple cannot be changed once it has been created. Tuples are created using parentheses (()) and can contain any type of data, including integers, floats, strings, lists, and dictionaries.
How to create a Python tuple
To create a Python tuple, you simply enclose the elements of the tuple in parentheses. For example:
Python
my_tuple = (1, 2, 3, 4, 5)
my_mixed_tuple = ("Hello, World!", 3.14, [1, 2, 3], {"name": "John Doe", "age": 30})
The first tuple contains only integers, while the second tuple contains a mix of different data types.
How to access items in a Python tuple
To access items in a Python tuple, you use the square bracket operator ([]) and the index of the item. The index of the first item in a tuple is 0. For example:
Python
print(my_tuple[0]) # Outputs 1
print(my_mixed_tuple[2]) # Outputs [1, 2, 3]
You can also use negative indices to access items from the end of the tuple. For example:
Python
print(my_tuple[-1]) # Outputs 5
print(my_mixed_tuple[-2]) # Outputs {"name": "John Doe", "age": 30}
How to iterate over a Python tuple
To iterate over a Python tuple, you can use the for loop. The for loop iterates over each item in the tuple and executes a block of code for each item. For example:
Python
for item in my_tuple:
print(item)
This code will print each item in the tuple to the console.
Python tuple methods
There are a few Python tuple methods that can be used to perform various tasks on tuples, such as counting the number of items in a tuple and finding the index of an item in a tuple.
Here are some examples of Python tuple methods:
Here are some additional tips for using Python tuples: