0

So, I have a project in which I have a list of strings:

outputs = ['cow', 'chicken', 'pig']

I need to turn them into a string, with each value separated by a newline, like so:

cow
chicken
pig

I found a solution at python list to newline separated value, but it uses a list like this:

outputs = [['cow'], ['chicken'], ['pig']]

and whenever I run:

 answer = "\n".join(map(lambda x: x[0], outputs))
 print(answer)

It returns 'c', as is the case with all the other answers in that question.

nbro
  • 15,395
  • 32
  • 113
  • 196
Decay X
  • 13
  • 1
  • 4

2 Answers2

8

You can join a list of strings by another string by simply using:

str = "\n".join(outputs)
Honza Zíka
  • 495
  • 3
  • 12
1

Your problem is that when you did:

map(lambda x: x[0], outputs)

You created an iterable consisting of the first letter of each element in outputs:

>>> outputs = ['cow', 'chicken', 'pig']
>>> list(map(lambda x: x[0], outputs))
['c', 'c', 'p']

Your over-thinking this. In this case, you don't even need to use map. You can simply use str.join:

'\n'.join(outputs)
Christian Dean
  • 22,138
  • 7
  • 54
  • 87