Reputation: 1204
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
Upvotes: 6
Views: 4019
Reputation: 142156
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...
Upvotes: 5
Reputation: 1778
The difference between list and tuple is that lists are mutable and tuples are immutable.
People tend to use tuples for heterogenous collections, similar to structs in C, and lists being for homogenous collections, similar to arrays in C.
Upvotes: 0