How is the usage of tuples in Python?
In Python, a tuple is an ordered and immutable sequence used to store multiple elements.
- Create a tuple.
- Separate multiple elements with commas and enclose them in parentheses: my_tuple = (1, 2, 3)
- You can create a tuple with commas only, omitting the parentheses: my_tuple = 1, 2, 3.
- Accessing tuple elements:
- You can access individual elements in a tuple using indexes, starting with 0: print(my_tuple[0]) # Output: 1
- You can access a subset of a tuple using slicing: print(my_tuple[1:3]) # Output: (2, 3)
- Modify the tuple:
- Tuples are immutable, meaning you cannot change the elements of a tuple. Attempting to modify a tuple will result in a TypeError.
- Operations on tuples:
- Tuples can perform several operations related to sequences, such as concatenating two tuples, repeating a tuple, and finding the index of an element.
- Unpacking a tuple:
- You can unpack the elements of a tuple and assign them to multiple variables: a, b, c = my_tuple.
- Length and number of elements of a tuple:
- You can use the built-in function len() to get the length of a tuple (i.e. the number of elements): print(len(my_tuple)) # Output: 3
In general, tuples in Python are used to store multiple related data items, they are immutable, making them suitable for situations where data immutability is desired.