0

Example:

from timeit import timeit

print(timeit("5 in [i for i in range(0, 100)]"))
print(timeit("5 in map(int, range(0, 100))"))

and this is result:

3.771566713000084
0.9066896029999043

python 3.8.5 (also I think this make no reference to python version ^_^)

Yuhui Wang
  • 49
  • 2
  • 8

2 Answers2

7

The in on map (which is an iterator, not a generator, technically speaking; generators are functions using yield or generator expressions, and they're a subset of the broader class of iterators) short-circuits as soon as it knows the result to be True, so it only actually produces and checks six values and then immediately returns True. The list comprehension, by contrast, must produce the entire list of 100 elements before checking any of them.

If your test was for an element that wasn't in the iterable in question, map's win, if any (the pointless call to int hurts it, performance-wise), would be smaller, but when the iterable contains the element, and it's early in the iterable, short-circuiting is clearly faster even if each element is more costly to produce, because it produces so many fewer elements.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

Generator expressions are much better than list comprehensions.

Iterating over the generator expression or the list comprehension will do the same thing. However, the list comprehension will create the entire list in memory first while the generator expression will create the items on the fly, so you are able to use it for very large and also even infinite sequences

Wasif
  • 14,755
  • 3
  • 14
  • 34
  • 3
    If generator expressions are much better than list comprehensions, then why did you use a list comprehension [here](https://stackoverflow.com/a/64862247/13008439)? – superb rain Nov 19 '20 at 02:09
  • @superbrain My preference (you can see in this answer i haven't promoted generator to use it) and to correct OP, you can see the same theme in my 300-400 answers – Wasif Nov 19 '20 at 02:11
  • 3
    "Generator expressions are much better than list comprehensions." is a rather absurd statement. You're comparing apples and oranges. The two things are completely different tools. If you want to make a list, use a list comprehension. If you want to make a generator, use a generator expression.... one is not "better" than the other any more than strings are "better" than numbers. – ggorlen Nov 19 '20 at 02:16
  • You're also simply not answering the question. Why one is so much *faster* than the other. – superb rain Nov 19 '20 at 14:49