I think the choices need to be considered strictly from the caller's point of view: what is the consumer most likely to need to do?
And what are the salient features of each collection?
- The tuple is accessed in order and immutable
- The list is accessed in order and mutable
- The dict is accessed by key
The list and tuple are equivalent for access, but the list is mutable. Well, that doesn't matter to me the caller if I'm going to immediately unpack the results:
score, top_player = play_round(players)
idx, record = find_longest(records)
There's no reason here for me to care if it's a list or a tuple, and the tuple is simpler on both sides.
On the other hand, if the returned collection is going to be kept whole and used as a collection:
points = calculate_vertices(shape)
# Make a new shape
then it might make sense for the return to be mutable. Homogeneity is also an important factor here. Say you've written a function to search a sequence for repeated patterns. The information I get back is the index in the sequence of the first instance of the pattern, the number of repeats, and the pattern itself. Those aren't the same kinds of thing. Even though I might keep the pieces together, there's no reason that I would want to mutate the collection. This is not a
Now for the dictionary.
the last one creates more readable code because you have named outputs
Yes, having keys for the fields makes heterogenous data more explicit, but it also comes with some encumbrance. Again, for the case of "I'm just going to unpack the stuff", this
round_results = play_round(players)
score, top_player = round_results["score"], round_results["top_player"]
(even if you avoid literal strings for the keys), is unnecessary busywork compared to the tuple version.
The question here is threefold: how complex is the collection, how long is the collection going to be kept together, and are we going to need to use this same kind of collection in a bunch of different places?
I'd suggest that a keyed-access return value starts making more sense than a tuple when there are more than about three members, and especially where there is nesting:
That leads into the next question: is the collection going to leave this scope intact, somewhere away from the call that created it? Keyed access over there will absolutely help understandability.
The third question -- reuse -- points to a simple custom datatype as a fourth option that you didn't present.
Is the structure solely owned by this one function? Or are you creating the same dictionary layout in many places? Do many other parts of the program need to operate on this structure? A repeated dictionary layout should be factored out to a class. The bonus there is that you can attach behavior: maybe some of the functions operating on the data get encapsulated as methods.
A fifth good, lightweight, option is
namedtuple(). This is in essence the immutable form of the dictionary return value.