Search code examples
pythonperformance

If in List vs For loop (performance)


I am curious to know what is faster in Python

Say I have a list

myList = ['a', 'b', 'c', 'd', 'e']

I have two ways of checking if an item is in the list.

if item in myList:
    # doSomthing()

or

for element in myList:
    if element == item:
        # doSomething()

I know that the first method is more "pythonic" but in terms of performance is there a difference?


Solution

  • Testing in jupyter notebook, the first option is significantly faster for a string search:

    Setup (from this question):

    rndm=''.join(choices(string.ascii_uppercase + string.digits, k=100000))
    

    Tests:

    %timeit 'a' in rndm
    26.2 µs ± 485 ns per loop
    
    %%timeit 
    for let in rndm: 
        if let=='a': 
            break
    2.42 ms ± 73.7 µs per loop
    

    Note: Even if we make a set() out of rndm and time the search, it still only comes in at 1.14 ms ± 26.9 µs per loop