Larry Freeman Larry Freeman - 6 months ago 8
Python Question

In python, is there a way to convert of list of integer-lists into a list of string-lists without creating a custom function?

Let's say that I have a list of integer-lists:

start=[[1,2,3],[4,5,6],[7,8,9]]


And I want to convert this into:

result=[["1","2","3"],["4","5","6"],["7","8","9"]]


I could solve this issue by creating my own function. Is there a way to solve it without a custom function?

def stringify(x):
return map(str,x)

start = [[1,2,3],[4,5,6],[7,8,9]]

result = map(stringify,start)

Answer

To make it as pythonic as possible, I would write:

result = [[str(subitem) for subitem in sublist] for sublist in start]

IMO, it is always better to write the most readable code, and list-comprehensions are sometimes faster than map.