Re: Converting a list of strings into a list of integers?

Discussion in 'Python' started by Ian Kelly, Jul 22, 2012.

  1. Ian Kelly

    Ian Kelly Guest

    On Sun, Jul 22, 2012 at 10:20 AM, Jan Riechers <> 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.

    Cheers,
    Ian
    Ian Kelly, Jul 22, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Roy Smith
    Replies:
    1
    Views:
    161
    Peter Otten
    Jul 22, 2012
  2. Jan Riechers
    Replies:
    4
    Views:
    214
  3. Paul Rubin
    Replies:
    0
    Views:
    160
    Paul Rubin
    Jul 22, 2012
  4. David Robinow
    Replies:
    0
    Views:
    163
    David Robinow
    Jul 22, 2012
  5. Jan Riechers
    Replies:
    0
    Views:
    149
    Jan Riechers
    Jul 22, 2012
Loading...

Share This Page