Mapping a nested list with List Comprehension in Python?

kjfletch picture kjfletch · Aug 20, 2009 · Viewed 11.8k times · Source

I have the following code which I use to map a nested list in Python to produce a list with the same structure.

>>> nested_list = [['Hello', 'World'], ['Goodbye', 'World']]
>>> [map(str.upper, x) for x in nested_list]
[['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']]

Can this be done with list comprehension alone (without using the map function)?

Answer

Eli Courtwright picture Eli Courtwright · Aug 20, 2009

For nested lists you can use nested list comprehensions:

nested_list = [[s.upper() for s in xs] for xs in nested_list]

Personally I find map to be cleaner in this situation, even though I almost always prefer list comprehensions. So it's really your call, since either will work.