2

pythonistas: which is faster, where a is something like [ str(x) for x in list(range(100)) ]?

ints = map(int, a)

Or

ints = [ int(x) for x in a ]

Assuming a will be a relatively large list of strings...

Wells
  • 10,415
  • 14
  • 55
  • 85
  • 2
    map will be faster, after that it is personal preference. map happens at the c level, once you are using map without a lambda with some builtin method it will generally be faster than doing the same in a list comp – Padraic Cunningham Apr 03 '16 at 22:53
  • 2
    CPython doesn't have most of the effects that make benchmarks hard for languages like C or Java, so you could just [time it](https://docs.python.org/2/library/timeit.html) and probably get the right answer. – user2357112 Apr 03 '16 at 22:55
  • read this :http://stackoverflow.com/a/1247490/4941927 I think that each a one could be helpful according to your need. – Milor123 Apr 03 '16 at 22:59

1 Answers1

5

map looks faster (without lambda) on my laptop (Macbook Pro Mid 2014, OSX 10.11.4, 16GB DDR3 ram, 2.2 GHz Intel Core i7):

Tested with Python 2.7.10

>>> timeit.timeit("[int(x) for x in range(100)]", number=100000)
1.6301331520080566

>>> timeit.timeit("map(int, range(100))", number=100000)
0.9462239742279053

However, using map with a lambda function is the slowest:

>>> timeit.timeit("map(lambda x: int(x), range(100))", number=100000)
2.285655994415283
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119