Ely Fialkoff
Ely Fialkoff

Reputation: 652

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?

Upvotes: 1

Views: 796

Answers (2)

Monik Patel
Monik Patel

Reputation: 1

Case 1:

if item in myList:

This will take O(1) time for N values.

O(1) means it will take the same time for N number of values, If your list has 1000 entries or 10 Lacs entries time taken by case 1 is the same.

Case 2:

for element in myList:
    if element == item:

This will take O(log(n)) time N values.

O(log(n)) means it will expressly time for N number of values, time will increase when the List has more values.

Upvotes: 0

G. Anderson
G. Anderson

Reputation: 5955

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

Upvotes: 4

Related Questions