1

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?

Ely Fialkoff
  • 642
  • 1
  • 5
  • 12
  • The way you've written it the first is faster in all but the degenerate case: there's no `break` in your `for` loop. The loop also has to create a binding (`element`) that the first version doesn't. – Jared Smith Oct 22 '18 at 17:56
  • I didn't add a `break` on purpose, obviously I can add one. With it in is the performance the same? – Ely Fialkoff Oct 22 '18 at 17:58

1 Answers1

4

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

G. Anderson
  • 5,815
  • 2
  • 14
  • 21