-1

I need help decomposing a nested list. For example:

a=[['we','got],['this','in'],['the','bag','man']]

into

b=['we','got','this','in','the','bag','man']

I've tried list comprehensions but continue getting index error when trying to do

x_1=[i[0] for i in a]
x_2=[i[1] for i in a]

It returns error i[1] is out of range for the list.

Dave
  • 23
  • 4
  • 1
    Hello, this is a commonly asked question on SO and the answer is here: [how to make a flat list out of list of lists](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – Rahul P Feb 25 '20 at 19:37
  • and you have a typo - `'got` doesn't have a closing quote – Maksim Skurydzin Feb 25 '20 at 19:38
  • 1
    Does this answer your question? [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – Maximouse Feb 25 '20 at 19:38
  • https://stackoverflow.com/a/20112805/701049 – tim Feb 25 '20 at 19:39

2 Answers2

2

Required code of above problem

a=[['we','got'],['this','in'],['the','bag','man']]
final=[x for b in a for x in b ]
print(final)
Welcome_back
  • 1,245
  • 12
  • 18
1
a=[['we','got'],["this",'in'],['the','bag','man']]
b=[]
for elementList in a:
    for element in elementList:
        b.append(element)

print(b)
Ratnesh
  • 1,554
  • 3
  • 12
  • 28
  • See this should work but when I insert it into my code print(b) returns ['w','e','t','h','i','s','t',h','e'] for some reason – Dave Feb 25 '20 at 19:45
  • @Dave, please execute it again as I have tested the above code and it is printing: `['we', 'got', 'this', 'in', 'the', 'bag', 'man']` – Ratnesh Feb 25 '20 at 19:50