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?

2
  • 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. Commented Oct 22, 2018 at 17:56
  • I didn't add a break on purpose, obviously I can add one. With it in is the performance the same? Commented Oct 22, 2018 at 17:58

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

The reason is that the first version runs mainly C code.
Agreed. Based on the question asked, "Is there a performance difference", I only answered with the "yes"
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.