Home > Enterprise >  How can I concate [['a'],['b'],['c']] this form of list into one strin
How can I concate [['a'],['b'],['c']] this form of list into one strin

Time:05-07

I want a simple solution,

I have this list:

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

And I want this result:

'abcdedefghdfsdf'

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 with join you will concatenate them. 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