Using lists and tuples in Python if statements

I am wondering if there are good reasons to prefer a list by tuple or vice versa in python ifstatments. So, are the following functionally equivalent, but 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 be used to using tuples if there are 2 or 3 values ​​and lists for something longer, I think because, in my experience, tuples tend to be short and long lists, but this seems a bit arbitrary and probably useless inconsistently.

I would be interested in any examples that people can give, where it is better to be better than others.

Greetings

+5
source share
2 answers

tuple ( , CPython) -, list, . , ( ).

. Python 2.7, ( ):

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

:

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

...

+5

, , .

, C, - , C.

0

All Articles