Here is the question:
Define a function named convert
that takes a list of numbers as its only parameter and returns a list of each number converted to a string.
For example, the call convert([1, 2, 3])
should return ["1", "2", "3"]
.
And this is my code:
def convert(li):
for i in range(len(li)): li[i] = str(li[i])
return li
But this will give me error as another line is used. How do i convert the code to one line?
CodePudding user response:
You could use
convert = lambda li: list(map(str, li))
or a list comprehension:
convert = lambda li: [str(e) for e in li]
CodePudding user response:
Here's a quick list comprehension to do this in a line.
def convert(li):
# For each item in the list, convert the integer to string:
print([str(i) for i in li])
convert([1, 2, 3])
CodePudding user response:
I can offer this solution:
def convert(li):
return list(map(str, li))