0

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.)

1
  • 1
    you are doing it backwards, the order of the for ... in a list comprehension should be the same as the equivalent regular for-loop Commented Aug 8, 2019 at 21:36

2 Answers 2

2

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)]
Sign up to request clarification or add additional context in comments.

Comments

1

So the main difference in your solution, is that the order of the generator part is switched.

To transform:

collection_c = []
for a in collection_a:
   for b in collection_b:
     collection_c.append(a,b)

You would want to do:

collection_c = [ (a,b) for a in collection_a for b in collection_b]

So in your example you would end up with

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.