1

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.

  • 1
    `return [str(a) for a in x]` – j1-lee Oct 25 '22 at 15:57
  • 1
    `convert = lambda x: [str(i) for i in x]` – Lecdi Oct 25 '22 at 15:58
  • 2
    @Lecdi [Avoid named lambdas](/q/38381556/4518341), use a `def` instead. I realize you're answering the question literally, but it's still bad practice. – wjandrea Oct 25 '22 at 16:10
  • Why are you both modifying `x` and returning `x`? [That's confusing and could easily cause bugs](/q/13062423/4518341). And it seems like it's not intentional because you accepted an answer that doesn't modify `x`. Please [edit] to clarify. While you're editing, please add details to the title, something like "How do I convert a list of ints to strings in one line?" [ask] has tips on writing a good title. – wjandrea Oct 25 '22 at 16:24

4 Answers4

4

Probably the shortest way:

def convert(x):
    return list(map(str, x))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Matei Piele
  • 572
  • 2
  • 15
3

You can use a list comprehension:

def convert(x):
    return [str(i) for i in x]
Fastnlight
  • 922
  • 2
  • 5
  • 16
2

Here

def convert(x):
    return [str(y) for y in x]
surge10
  • 622
  • 6
  • 18
2

Using list comprehension

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

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