1

I am trying to convert the list of input words ['hdjk', 'salsap', 'sherpa'] to output: 'hdjk salsap sherpa' using the reduce()

Here is the code I am trying to work on:

from functools import reduce
input_list =  ['hdjk', 'salsap', 'sherpa']
list(reduce(lambda x,y: x+" "+y, input_list)) # This gives irrelevant output

I have also tried this:

xinpl = [x.split() for x in input_list]
list(reduce(lambda x,y: x+" "+y, xinpl))

This code joins all the elements in the input_list and it works for me

print(" ".join(input_list))  

I looked at other similar threads and been trying this a lot: Make List to String Python

I am still a learner. Gurus can your please help?

6
  • 2
    Can you explain why you'd want reduce and not " ".join? Commented Aug 5, 2018 at 5:17
  • Remove the list in list(reduce(...)) and it works. Commented Aug 5, 2018 at 5:18
  • nevermind, I found the answer: Commented Aug 5, 2018 at 5:21
  • @ StardustGogeta, thanks it worked. :-) Commented Aug 5, 2018 at 5:23
  • 1
    @coldspeed, Since I am still a learner I was exploring and trying other ways of achieving the same output through different ways. Commented Aug 5, 2018 at 13:57

2 Answers 2

3

The reduce part of the code is working just fine. The only problem is that it is returning a string, which is then converted to a list. Simply remove the list in list(reduce(...)) and it works as expected.

>>> from functools import reduce
>>> input_list =  ['hdjk', 'salsap', 'sherpa']
>>> reduce(lambda x,y: x+" "+y, input_list)
'hdjk salsap sherpa'
Sign up to request clarification or add additional context in comments.

Comments

0
input_list = ['All','you','have','to','fear','is','fear','itself']

from functools import reduce

string1 = str(reduce(lambda x,y: x + " " +y, input_list))

print(string1)

1 Comment

consider adding an explanation to your code so that it will help the OP?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.