How is the usage of tuples in Python?

In Python, a tuple is an ordered and immutable sequence used to store multiple elements.

  1. Create a tuple.
  2. Separate multiple elements with commas and enclose them in parentheses: my_tuple = (1, 2, 3)
  3. You can create a tuple with commas only, omitting the parentheses: my_tuple = 1, 2, 3.
  4. Accessing tuple elements:
  5. You can access individual elements in a tuple using indexes, starting with 0: print(my_tuple[0]) # Output: 1
  6. You can access a subset of a tuple using slicing: print(my_tuple[1:3]) # Output: (2, 3)
  7. Modify the tuple:
  8. Tuples are immutable, meaning you cannot change the elements of a tuple. Attempting to modify a tuple will result in a TypeError.
  9. Operations on tuples:
  10. Tuples can perform several operations related to sequences, such as concatenating two tuples, repeating a tuple, and finding the index of an element.
  11. Unpacking a tuple:
  12. You can unpack the elements of a tuple and assign them to multiple variables: a, b, c = my_tuple.
  13. Length and number of elements of a tuple:
  14. 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.

bannerAds