0

I have a lists of lists of strings which I would like to convert to a list of strings adding a space between each list item. eg.

original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']]

desired_output = ['the cat in the hat', 'fat cat sat on the mat']

I understand that I can do it using this:

desired_output
for each in original_list:
    desired_output.append(' '.join(each))

but as I am working with large amounts of data am ideally looking for a more efficient way to do this.

2
  • It should be ' '.join(each) instead of ''.join(each) in your code Commented Oct 20, 2017 at 15:34
  • 2
    @KaushikNP Cheers - it was a typo. Commented Oct 20, 2017 at 15:35

2 Answers 2

4

Use str.join with a full space ' ':

original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']]
final_list = [' '.join(i) for i in original_list]

Output:

['the cat in the hat', 'fat cat sat on the mat']
Sign up to request clarification or add additional context in comments.

4 Comments

Um, how is this an optimisation? The OP has already done this, just not using list comprehension.
@KaushikNP str.join is much faster than string concatenation because strings are immutable and thus cannot be changed in place.
But that's not what the user has done. The OP too has used join. But yeah, one thing I overlooked. The user used append and list comprehension has a slight advantage there. So works out. +1
@KaushikNP it also optimised LOCs, reducing dev time ;)
1

Another pythonic and simple way, in Python 3, could be using map, says another SO discussion it should be faster, it would go like this:

original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']]

#              (------where magic happens--------)
desired_list = list(map(' '.join, original_list ))

#print
#output ['the cat in the hat', 'fat cat sat on the mat']

Comments

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.