I'm 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, in Python 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.
New and neat in Python 3.5:
Thanks to Additional Unpacking Generalizations
UPDATE
Always seeking for shorter ways, I discovered this one also works:
Unpacking works in tuples too. Note the comma at the end. This makes it a tuple of 1 element. That is, it's equivalent to
(*map(chr, [66, 53, 0, 94]),)
It's shorter by only one char from the version with the list-brackets, but, in my opinion, better to write, because you start right ahead with the asterisk - the expansion syntax, so I feel it's softer on the mind. :)
In addition to above answers in
Python 3
, we may simply create alist
of result values from amap
asWe may generalize by another example where I was struck, operations on map can also be handled in similar fashion like in
regex
problem, we can write function to obtainlist
of items to map and get result set at the same time. Ex.Why aren't you doing this:
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.
Do this:
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:Using list comprehension in python and basic map function utility, one can do this also:
chi = [x for x in map(chr,[66,53,0,94])]
Converting my old comment for better visibility: For a "better way to do this" without
map
entirely, if your inputs are known to be ASCII ordinals, it's generally much faster to convert tobytes
and decode, a labytes(list_of_ordinals).decode('ascii')
. That gets you astr
of the values, but if you need alist
for mutability or the like, you can just convert it (and it's still faster). For example, inipython
microbenchmarks converting 45 inputs:If you leave it as a
str
, it takes ~20% of the time of the fastestmap
solutions; even converting back to list it's still less than 40% of the fastestmap
solution. Bulk convert viabytes
andbytes.decode
then bulk converting back tolist
saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g.latin-1
).