Contents

Python Tuples

Website Visitors:
Contents

Tuples in Python

In Python, a tuple is an ordered collection of items, similar to a list. However, unlike lists, tuples are immutable, which means their elements cannot be modified once defined. Tuples are defined by enclosing the items in parentheses ( ) and separating them with commas. Tuples can be useful when we need to ensure that an element is in a certain position and will not change.

Here are the full details about tuples in Python:

  1. Creating a Tuple:

    1
    
    my_tuple = (1, 2, 3)
    

    In this example, we created a tuple called my_tuple with three elements: 1, 2, and 3.

  2. Accessing Elements:

    1
    
    print(my_tuple[0])  # Output: 1
    

    Similar to lists, tuples are zero-indexed, so you can access individual elements using their index.

  3. Immutable Nature:

    1
    
    my_tuple[1] = 4  # Raises TypeError: 'tuple' object does not support item assignment
    

    Tuples are immutable, so you cannot modify the value of an element once it is assigned.

  4. Tuple Length:

    1
    
    print(len(my_tuple))  # Output: 3
    

    The len() function returns the number of elements in a tuple.

  5. Concatenating Tuples:

    1
    2
    
    new_tuple = my_tuple + (4, 5)
    print(new_tuple)  # Output: (1, 2, 3, 4, 5)
    

    You can concatenate two tuples using the + operator, resulting in a new tuple.

  6. Tuple Packing and Unpacking:

    1
    2
    3
    
    my_tuple = 1, 2, 3  # Packing
    a, b, c = my_tuple  # Unpacking
    print(a, b, c)  # Output: 1 2 3
    

    Tuple packing is the process of creating a tuple without explicitly using parentheses. Tuple unpacking allows assigning the elements of a tuple to separate variables.

  7. Iterating over a Tuple:

    1
    2
    
    for item in my_tuple:
      print(item)
    

    You can use a for loop to iterate over the elements of a tuple.

  8. Tuple Methods: Tuples have limited built-in methods due to their immutable nature. However, they inherit some methods from the object class, such as count() and index(), which can be used to count occurrences of an element or find its index in the tuple.

  9. Iterating over tuples

    1
    2
    3
    4
    5
    6
    7
    
    def full_emails(people):
      result = []
      for email, name in people:
        result.append("{} <{}>".format(name, email))
      return result
    print(full_emails([("alex@example.com", "Alex Diego"), ("shay@example.com", "Shay Brandt")])) 
    #output ['Alex Diego <alex@example.com>', 'Shay Brandt <shay@example.com>']
    
  10. We can directly add the results into variables as we know the placeholders in tuples wont change.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    def convert_seconds(seconds):
      hours = seconds // 3600
      minutes = (seconds - hours * 3600) // 60
      remaining_seconds = seconds - hours * 3600 - minutes * 60
      return hours, minutes, remaining_seconds
      result = convert_seconds(5000)
      hours, minutes, seconds = result
      print(hours, minutes, seconds)
    # In the output variable called result, we have hours, minutes, and seconds.
    # Since the first value is hours, second value is minutes and third value is seconds,
    # We can call the values directly without using result variable
    def convert_seconds(seconds):
      hours = seconds // 3600
      minutes = (seconds - hours * 3600) // 60
      remaining_seconds = seconds - hours * 3600 - minutes * 60
      return hours, minutes, remaining_seconds
      hours, minutes, seconds = convert_seconds(1000)
      print(hours, minutes, seconds)
    
  11. Lists in Tuples

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    # A tuple with a list as an element
    my_tuple = (1, 2, ['a', 'b', 'c'])
    
    # You can't change the tuple itself
    # my_tuple[0] = 3  # This would raise a TypeError
    
    # But you can modify the mutable elements within the tuple
    my_tuple[2][0] = 'x'  
    print(my_tuple)  # Outputs: (1, 2, ['x', 'b', 'c'])
    

Tuples are commonly used when you want to group related data together that should not be modified. They are useful in scenarios where you want to ensure data integrity and prevent accidental modifications. Examples include representing coordinates, database records, and returning multiple values from a function.

Note that although tuples themselves are immutable, they can contain mutable objects such as lists. In such cases, the mutable objects within the tuple can be modified, even though the tuple itself remains immutable.

Overall, tuples offer a lightweight and efficient way to store and access data when immutability is desired.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.