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
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With