How to write this function in one line of code?

Question:

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.

Asked By: ianikdobrevser

||

Answers:

You can use a list comprehension:

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

Probably the shortest way:

def convert(x):
    return list(map(str, x))
Answered By: Matei Piele

Here

def convert(x):
    return [str(y) for y in x]
Answered By: surge10

Using list comprehension

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

>> ['1', '2', '3']
Answered By: RuntimeError
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.