Click here to Skip to main content
15,886,068 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Python
[j for i in x for j in range(len(x)) if i == x[j]]

that is list comprehension the question is: is the loop ( for i in x) nested in the loop (for j in range(len(x)) or the converse?

What I have tried:

the ............................................loops
Posted
Updated 11-Jul-20 23:33pm
v2

Apart for not compiling as is, so the code sample you show won't work, give it a try: replace the "if" with a print statement and show the values of i and j.
Whichever goes up first is the inner loop.
 
Share this answer
 
Comments
Richard MacCutchan 12-Jul-20 5:31am    
Runs fine in my Python.
Using a simple example we get the equivalent shown here:
Python
    x = [ 2, 3, 4, 7, 11 ]
    z = [j for i in x for j in range(len(x)) if i == x[j]]
    print(z)

# which is the same as
    zzz = []
    for i in x:
        for j in range(len(x)):
            if i == x[j]:
                zzz.append(j)
    print(zzz)

And the output is:
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900