Python Interview Questions

Steven D'Aprano steve+comp.lang.python at
Sun Nov 18 17:50:52 CET 2012

On Sun, 18 Nov 2012 08:53:25 -0500, Roy Smith wrote:

> In article <50a8acdc$0$29978$c3e8da3$5496439d at>,
>  Steven D'Aprano <steve+comp.lang.python at> wrote:
>> Use a list when you want a list of items that should all be treated the
>> same way [...] or when you need a collection of items where the order
>> they are in is important:
>> Use a tuple when you want a collection of items that mean different
>> things, a bit like a C struct or Pascal record:
> That is certainly the right answer according to the One True Church Of
> Pythonic Orthodoxy And Theoretical Correctness.

Oh I'm sorry, did something I say suggest that the couple of examples I 
gave are the *only* acceptable uses? My apologies for not giving an 
exhaustive list of every possible use of lists and tuples, I'll be sure 
to punish myself severely for the lapse.

> But, let me give an
> alternative answer which works for The Unwashed Masses Who Live In The
> Trenches And Write Python Code For A Living:
> Use a list when you need an ordered collection which is mutable (i.e.
> can be altered after being created).  Use a tuple when you need an
> immutable list (such as for a dictionary key).

I keep hearing about this last one, but I wonder... who *actually* does 
this? I've created many, many lists over the years -- lists of names, 
lists of phone numbers, lists of directory search paths, all sorts of 
things. I've never needed to use one as a dictionary key.

Under what sort of circumstances would somebody want to take a mutable 
list of data, say a list of email addresses, freeze it into a known 
state, and use that frozen state as a key in a dict? What would be the 
point? Even if there was some meaningful reason to look up "this list of 
12000 email addresses" as a single key, it is going to get out of sync 
with the actual mutable list.

Sure, I have built a collection of items as a list, because lists are 
mutable, then frozen it into a tuple, and *thrown the list away*, then 
used the tuple as a key. But that's not the same thing, the intent is 
different. In my case, the data was never intended to be a list, it was 
always intended to be a fixed record-like collection, the use of list was 
as a temporary data structure used for construction. A bit like the idiom 
of ''.join(some_list).

But I can't think of any meaningful, non-contrived example where I might 
want an actual mutable list of values as a dict key.


More information about the Python-list mailing list