Configuration values are gathered once and then treated as a fixed sequence.
What You Need to Understand
tuple(iterable) constructs an immutable ordered sequence. It accepts any finite iterable, and calling tuple() without arguments creates an empty tuple.
When to Use It
Configuration values are gathered once and then treated as a fixed sequence.
Step-by-Step Python Example
values = [10, 20, 30]
fixed_values = tuple(values)
values.append(40)
print(fixed_values)
print(tuple("go"))
How the Example Works
The tuple retains the three references that existed when it was created; subsequent appends to the outer list do not change its length.
Example Output
(10, 20, 30)
('g', 'o')
(0, 1, 2)
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
readings = tuple(range(3))
print(readings)
Important Behavior and Edge Cases
A tuple containing nested mutable objects is not deeply immutable. Tuple creation from an infinite iterator will not terminate.
Try It Yourself
Convert a range of three integers to a tuple and unpack its values.
Common Beginner Mistakes
- A tuple containing nested mutable objects is not deeply immutable. Tuple creation from an infinite iterator will not terminate.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
tuple(iterable)constructs an immutable ordered sequence.- The tuple retains the three references that existed when it was created; subsequent appends to the outer list do not change its length.
- A tuple containing nested mutable objects is not deeply immutable.