0

I have what is probably a trivial Python question, I have a list of lists of tuples in the following format:

lis1=[[(1,2),(3,4)],[(5,6),(7,8)]]

which I want to convery to a single list of tuples with ideally a space between the lists, like so:

lis2=[1,2,3,4, ,5,6,7,8]

or simply as a single list:

lis3=[1,2,3,4,5,6,7,8]

what would be the fastest way to achieve this?

Thanks!

Edit

So far I have tried:

lis3=[w for w in term for term in lis1]

and a for loop

lis3=[]
for term in lis1:
    for w in term:
        lis3.append(w)

which works, but I am really looking for a single line implementation and to avoid the .append() function.

Answer

you've mixed outer and inner loops in the list comprehension. Imagine you have a multiline code: for inner_list in outer_list: for item in inner_list: result.append(item) then the same as a list comprehension: result = [item for inner_list in outer_list for item in inner_list] note: the order of the loops is exactly the same. – J.F. Sebastian

kat
  • 163
  • 7
  • 1
    You cannot have a 'space' between elements. Perhaps use `None` instead. – Martijn Pieters Oct 02 '14 at 13:08
  • Fast for the computer to execute, or fast for the programmer to write? – Kevin Oct 02 '14 at 13:09
  • Thanks, I just found the duplicate question ([item for sublist in lis1 for item in sublist]). Feeling silly.. – kat Oct 02 '14 at 13:11
  • you've mixed outer and inner loops in the list comprehension. Imagine you have a multiline code: `for inner_list in outer_list: for item in inner_list: result.append(item)` then the same as a list comprehension: `result = [item for inner_list in outer_list for item in inner_list]` note: the order of the loops is exactly the same. – jfs Oct 02 '14 at 16:25
  • Thak you! I managed to get it working but @J.F.Sebastian you've explained it to me :) – kat Oct 03 '14 at 11:31

0 Answers0