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
  • 13,796
  • 25
  • 99
  • 185
Decay X
  • 13
  • 4

2 Answers2

7

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

str = "\n".join(outputs)
Honza Zíka
  • 485
  • 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
  • 20,986
  • 7
  • 47
  • 78