Home > Mobile >  How to write this function in one line of code?
How to write this function in one line of code?

Time:10-26

I have this code that converts all int elemets of a list to strings:

def convert(x):
    for i in range(0, len(x)):
        x[i] = str(x[i])
    return x

How can I write the function in only one line, using map()?

Tried writing the for loop in one line but it doesn't seem to work.

CodePudding user response:

Probably the shortest way:

def convert(x):
    return list(map(str, x))

CodePudding user response:

You can use a list comprehension:

def convert(x):
    return [str(i) for i in x]

CodePudding user response:

Using list comprehension

ints = [1, 2, 3]
result = [str(x) for x in ints]
print(result)

>> ['1', '2', '3']

CodePudding user response:

Here

def convert(x):
    return [str(y) for y in x]
  • Related