Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lists and tuples in Python if statements

I'm wondering whether there are any good reasons to prefer a list over a tuple or vice versa in python if statments. So the following are functionally equivalent but is one preferable to the other in terms of performance and coding style or does it not matter?

if x in (1,2,3):
    foo()

if x in [1,2,3]:
    foo()

I seem to have gotten into the habit of using tuples if there are 2 or 3 values and lists for anything longer, I think because in my experience tuples tend to be short and lists long, but this seems a bit arbitrary and probably needlessly inconsistent.

I'd be interested in any examples people can give of where one would be better than the other.

Cheers

like image 589
redrah Avatar asked Sep 13 '12 15:09

redrah


1 Answers

The initialisation of a tuple (at least in CPython) produces less bytecode than a list - but it's really nothing to worry about. I believe membership testing is pretty much the same (although not tested it).

For purely membership testing the lookup semantics are the same. From Python 2.7 onwards, it's much nicer to write (and adds an implication that it's membership testing only):

if x in {1, 2, 3}:
    pass # do something

While prior to that:

if x in set([1,2,3]):
    pass # do something

just looked a little kludgy...

like image 140
Jon Clements Avatar answered Oct 23 '22 15:10

Jon Clements