Which type should be used when testing static structure appartenance

Chris Angelico rosuav at gmail.com
Tue Nov 17 10:28:31 EST 2015


On Wed, Nov 18, 2015 at 1:27 AM, Nicolas Évrard <nicoe at altern.org> wrote:
> I saw just in time because in a review I wrote something like this:
>
>    if operator not in ('where', 'not where')
>
> and my colleague proposed that I should use a list instead of a tuple.
> But reading the mentioned tweet I tend to think that a set would be a
> better choice.
>
> What are your opinion on this issue (I realize it's not something of
> the utmost importance but rather a "philosophical" question).

Definitely a set. I don't know why it would be better to use a list;
there's no advantage here for the list. "x [not] in some_set"
accurately represents the concept of "any of these will match". With a
two-element list/tuple/set, I doubt there's going to be any
significant performance difference, but if anything, I would expect
the tuple to be the fastest (because it can be stored as a literal),
and the other two need to be built; but CPython's optimizer has me
beat there - they're all stored as literals (the list becomes a tuple,
the set becomes a frozenset), meaning there's basically no difference.
So you're free to use the one that expresses the concept of "is this
part of this set of strings", which is the set.

ChrisA



More information about the Python-list mailing list