Home > Back-end >  How can I concatenate [['a'],['b'],['c']] this form of list into one s
How can I concatenate [['a'],['b'],['c']] this form of list into one s

Time:05-07

I have this list:

[['abcde'],['defgh'],['dfsdf']]

And I want this result:

'abcdedefghdfsdf'

I want a simple solution.

CodePudding user response:

Try this in one line:

"".join([i[0] for i in a])

It will loop over the items and turns them into ['abcde','defgh','dfsdf']. Then you will concatenate them with join.

So the result will be:

Out[4]: 'abcdedefghdfsdf'

Take a look at this link to learn more about .join().

As FreddyMcloughlan said in comments:

You could change the square brackets to parenthesis to turn it into a generator if working with very large lists

CodePudding user response:

Try this snippet:

str_lists = [['abcde'],['defgh'],['dfsdf']]
output_str = "".join([lst.pop() for lst in str_lists])

"".join() is used to concatenate strings together from a list, while the inner list comprehension is used to flatten the list of lists into a single list

  • Related