views:

665

answers:

3

Hello world,

Im trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:

A: python 2.6:

>>> map(chr,[66,53,0,94])
['B', '5', '\x00', '^']

However, on 3.1, the above returns a map object.

B: python 3.1:

>>> map(chr,[66,53,0,94])
<map object at 0x00AF5570>

How do i retrieve the mapped list (as in A above) on python 3.x?

Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.

+7  A: 

Why aren't you doing this:

[chr(x) for x in [66,53,0,94]]

It's called a list comprehension. You can find plenty of information on Google, but here's the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.

Mark Rushakoff
Yes to list comprehensions.
hughdbrown
Thanks, didnt know about list comprehension :)
mozami
Hmmmm. Maybe there needs to be a general posting on list comprehensions, generators, map(), zip(), and a lot of other speedy iteration goodness in python.
hughdbrown
*sigh* Does anyone ever actually just read the tutorial anymore?
John Y
I guess because it's more verbose, you have to write an extra variable (twice)... If the operation is more complex and you end up writing a lambda, or you need also to drop some elements, I think a comprehension is definitively better than a map+filter, but if you already have the function you want to apply, map is more succinct.
fortran
+11  A: 

Do this:

list(map(chr,[66,53,0,94]))

In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.

If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the map object like so:

# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
    print(ch)
Triptych
Thank you for the great explanation!!
mozami
..of course, the `print` statement doesn't exinst in python 3.0 :-)
John Fouhy
Of course, you can iterate over this, too: (chr(x) for x in [65,66,67,68]). It doesn't even need map.
hughdbrown
@john. haha oops.
Triptych
@hughdbrown The argument for using 3.1's `map` would be lazy evaluation when iterating on a complex function, large data sets, or streams.
Andrew Keeton
@Andrew actually Hugh is uing a generator comprehension which would do the same thing. Note the parentheses rather than square brackets.
Triptych
@Triptych: saved me the trouble of saying the same thing.
hughdbrown
+3  A: 

I'm not familiar with Python 3.1, but will this work?

[chr(x) for x in [66, 53, 0, 94]]
Andrew Keeton
Yep, it works perfectly too.
mozami