In Python, tuples are a fundamental data type used to store a collection of items. They are similar to lists, but unlike lists, tuples are immutable, which means that their values cannot be changed after they are created. They are written using parentheses and separated by commas. For example:
1tuple_literal = (1, 2, 3, 4, 5)
Tuples are often used to store a collection of related values, such as the x and y coordinates of a point. They can also be used as keys in a dictionary, since they are immutable and can be hashed, while lists cannot.
Python also provides several built-in functions and methods for working with tuples, such as counting, indexing, and slicing. These functions and methods allow you to perform a wide range of operations on tuples, such as finding the number of times an element appears in a tuple or accessing a specific element.
1numbers = (1, 2, 3, 4, 5, 3) 2print(numbers.count(3)) # Output: 2 3print(numbers) # Output: 3
In addition, you can use tuple unpacking to assign the elements of a tuple to separate variables.
1x, y, z = (1, 2, 3) 2print(x) # Output: 1 3print(y) # Output: 2
Creating a Tuple
Tuples are created using parentheses
(). You can also create a tuple by separating the items with commas without parentheses.
1# Creating a Tuple 2my_tuple = (1, 2, 3) 3print(my_tuple) 4 5# Tuple without Parentheses 6my_tuple2 = 4, 5, 6 7print(my_tuple2)
Accessing Tuple Elements
You can access tuple elements using indexing. In Python, indexing starts at 0. You can also access multiple elements using slicing.
1# Accessing Tuple Elements 2my_tuple = ('a', 'b', 'c', 'd', 'e') 3print(my_tuple) 4print(my_tuple[-1]) 5print(my_tuple[1:4])
Tuples are immutable, meaning that you cannot change their values once they are created. However, you can create a new tuple with updated values.
1# Updating Tuples 2my_tuple = (1, 2, 3) 3new_tuple = my_tuple + (4, 5, 6) 4print(new_tuple)
Since tuples are immutable, you cannot delete individual elements. However, you can delete the entire tuple.
1# Deleting Tuples 2my_tuple = (1, 2, 3) 3del my_tuple
Tuples have only two methods:
1# Tuple Methods 2my_tuple = (1, 2, 3, 1, 2, 3) 3print(my_tuple.count(1)) 4print(my_tuple.index(2))
Advantages of Tuples
- Tuples are faster than lists.
- Tuples can be used as keys in dictionaries, while lists cannot.
- Tuples can be used in a variety of situations where you want to ensure that the data is not changed.