0

Here is my list.

[['john'],
 ['tom','peter'],
 ['sam'],
 ['mary','susan','dan'],
   :
 ['tony']]

I would like to remove all the square brackets and break down the list that looks like below.

['john',
 'tom',
 'peter',
 'sam',
 'mary',
 'susan',
 'dan',
   :
 'tony']

I tried to use new_lst = ','.join(str(v) for v in lst) and (','.join(lst)) but they don't work. And I couldn't think of a way to break down those list elements as well. That will be great if you all have some ideas and approaches on how to do that.

Thanks!

rv.kvetch
  • 5,465
  • 3
  • 10
  • 28
CodingStark
  • 189
  • 2
  • 11

2 Answers2

4

Two good ways:

out = list(x for y in lst for x in y)
...or...
out = sum(lst,[])
Tim Roberts
  • 34,376
  • 3
  • 17
  • 24
2

Here is a quick way:

my_list = [['john'],
 ['tom','peter'],
 ['sam'],
 ['mary','susan','dan'],
 ['tony']]

# flatten the list
my_list = [item for sublist in my_list for item in sublist]
print(my_list)
Mohammad
  • 3,074
  • 2
  • 18
  • 32