Search code examples
pythonlistfor-loopnested-loops

Writing a single-line nested loop in Python


I'm trying to compress a for loop inside of another for loop into a single line of code. This is the full nested loop:

list_of_numbers = []

for i in range(4):
    for n in range(4):
        list_of_numbers.append(n)

I thought that the below line of code would be the correct way of writing the above code as a single-line nested loop, but it gave the wrong output.

list_of_numbers = [n for n in range(4) for i in range(4)]

How would this second example of code be modified to do the same as the first?

(This question has been reworded, so any answers given before the 13th of August 2019 will be answering the same question using a previous example.)


Solution

  • Possibly counter intuitively, in a nested list comprehension you need to follow the same order of the for loops as with the longhand version. So:

    [data[((len(data) - 1) - (8 * i)) - (7 - n)] for i in range(int(len(data) / 8)) for n in range(8)]