Converting a list of strings into a list of integers?

Ian Kelly ian.g.kelly at
Sun Jul 22 19:16:26 CEST 2012

On Sun, Jul 22, 2012 at 10:20 AM, Jan Riechers <janpeterr at> wrote:
> Hi,
> I am not sure why everyone is using the for-iterator option over a "map",
> but I would do it like that:
> MODUS_LIST= map(int, options.modus_list)
> "map" works on a list and does commandX (here "int" conversion, use "str"
> for string.. et cetera) on sequenceY, returning a sequence. More in the help
> file.
> And if I'm not completely mistaken, it's also the quicker way to do
> performance wise. But I can't completely recall the exact reason.

My recollection is that map has the edge if you can pass it a built-in
or a C extension function, like int, or a complicated Python function
that you would end up calling anyway in the list comprehension.  The
situation changes though if you can write the comprehension to remove
the overhead of the Python function call.  For example:

map(lambda x: x+1, my_list)

[x+1 for x in my_list]

By performing the addition inline instead of calling a function to do
it, the list comprehension wins performance-wise in this scenario.  So
as a simple rule of thumb I will typically choose between map or a
comprehension based on whether I need to call a function or not (and
also based on how pretty or ugly the resulting code is).  Anything
further would just be premature optimization.  Also keep in mind that
in Python 3 map returns an iterator instead of a list, so for a fair
comparison you would have to compose the map with a list() call.


More information about the Python-list mailing list