Programming in Python: Tuples and Sequences

Tuples in Python are immutable sequences, meaning their elements cannot be changed after assignment. They are typically used for grouping related data.

Creating Tuples

A tuple consists of elements enclosed in parentheses, although parentheses are optional. An empty tuple is represented as ().

# Creating tuples
empty_tuple = ()
print(empty_tuple)  # Output: ()

single_element_tuple = ('one',)  # Note the comma!
print(single_element_tuple)  # Output: ('one',)

multi_element_tuple = ('one', 'two', 'three')
print(multi_element_tuple)  # Output: ('one', 'two', 'three')

Why the Comma in a Single-Element Tuple?

If you don’t include a trailing comma, Python will not recognize it as a tuple:

not_a_tuple = ('one')
print(type(not_a_tuple))  # Output: <class 'str'>

single_element_tuple = ('one',)
print(type(single_element_tuple))  # Output: <class 'tuple'>

Tuple Packing and Unpacking

Tuple packing refers to grouping multiple values into a tuple, while unpacking extracts those values into variables.

# Packing values into a tuple
t = 1223, 5676, 'one', 'two'  # Parentheses are optional here
print(t)  # Output: (1223, 5676, 'one', 'two')

# Unpacking the tuple
a, b, c, d = t
print(a)  # Output: 1223
print(d)  # Output: 'two'

Extended Unpacking (Python 3.0+)

Python allows using * to capture multiple elements during unpacking:

t = (1, 2, 3, 4, 5)

first, *middle, last = t
print(first)   # Output: 1
print(middle)  # Output: [2, 3, 4]
print(last)    # Output: 5

Immutable Nature of Tuples

Tuples are immutable, meaning elements cannot be changed after assignment:

t = (1, 2, 3)
t[0] = 10  # TypeError: 'tuple' object does not support item assignment

However, if a tuple contains mutable elements (like lists), those elements can still be modified:

t = (1, [2, 3], 4)
t[1].append(5)  # Modifying the list inside the tuple
print(t)  # Output: (1, [2, 3, 5], 4)

When to Use Tuples?

  • When you need an immutable sequence of elements.
  • When returning multiple values from a function.
  • As dictionary keys (since lists are not hashable).
  • For performance optimization since tuples are slightly faster than lists.

Conclusion

Tuples are a fundamental data structure in Python, providing an immutable sequence type. With tuple packing and unpacking, they allow for convenient assignment and handling of multiple values. While lists are more flexible, tuples serve an important role where immutability is needed.