[Python] The most efficient way in Python to test if an element belongs to certain category

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    So I have a loop in Python and I want to test if elements belong to some category:

    for element in some_iterator():
    if element in collection:
    do_something()


    Question: what should be the class of collection for this code to be optimal?

    I'm guessing that if I construct the collection outside of function, the best one would be set. But if I want to use a literal, the set will need to be constructed on every call.

    How to balance between construction time and testing time? Is list the best option after all?

    Continue reading...

Compartilhe esta Página