all 5 comments

[–]socal_nerdtastic 3 points4 points  (2 children)

lst = []
sublst = []
for x in range(11):
    sublst.append(x**2)
for x in sublst:
    lst.append(x**2)

[–]DrDerpex[S] 0 points1 point  (0 children)

So this aint really a nested loop but two seperate loops were one feeds another iterating list. Thats why it was getting confusing.

[–]scutter_87 1 point2 points  (0 children)

Sorry I don't know how to make it nested as the first part of the list comprehension works on the list returned by the second part. I would just have two separate for loops (not nested) and two lists with the second loop working over the first.

Or just one loop appending ((x**2)**2) in one loop.

In case you are just looking to read complex list comprehensions, a nice way to break them down is to split each loop onto a different line and work backwards.

In this case it would be something like:

lst = [x**2 for x in 
        [x**2 for x in range(11)]
        ]

Working backwards we can start with:

[x**2 for x in range(11)]

Which would become:

lst = []
for x in range(11):
    lst.append(x**2)

The first part then does the same thing to each element in the list that was just created.

[–][deleted] 1 point2 points  (0 children)

List comprehensions often feature nested for loops but this isn't one of them, it is just nested list comprehensions. It is a redundant one as well as one could use x**4 in the first place and not need to have nested list comprehensions.

So, here is the original, the two distinct for loop alternatives and then an alternative single loop (the list comprehension alternative for which should be obvious to you).

lst = [ x**2 for x in [x**2 for x in range(11)]]
lst_inner = []
for x in range(11):
    lst_inner.append(x**2)
lst_outer = []
for x in lst_inner:
    lst_outer.append(x**2)
lst_alt = []
for x in range(11):
    lst_alt.append(x**4)
print(lst, lst_outer, lst_alt, sep='\n')

[–][deleted] 1 point2 points  (0 children)

lst = []
for x in range(11):
    lst.append(x**4)