Junior — Middle
In what situations is it recommended to use tuples in programming?
sobes.tech AI
Answer from AI
Tuples in Python are recommended when you need to store an immutable sequence of elements. This is useful if the data should not change after creation, ensuring safety and predictability of the code.
Examples of situations:
- Storing fixed sets of values, such as coordinates (x, y).
- Using as dictionary keys, since tuples are hashable, whereas lists are not.
- Passing multiple values from a function when there is no need to modify the returned data.
point = (10, 20) # coordinates of the point
# a tuple can be used as a dictionary key
location_data = {point: "Park"}