Don"t understand a part of quick union code

Don"t understand a part of quick union code
0

i am study the quick union in coursera and implement it in python.
but a part of code can’t understand.is tree data structure need to learn first?

id=[i for i in range(10)]
def root(i):
    while i!=id[i]: #this part can not understand,how this declare the root and the loop works
        print(i)
        i=id[i]
    return i    

def union(p,q):
    i=root(p)
    j=root(q)
    id[i]=j

def check(p,q):
    return root(p)==root(q)
union(2,3)
print(root(2))

i hope someone help me to understand this topic.thank you in advance.

Change the parameter ‘i’ in function root to another letter may help you understand it. And some prints will make you see what’s going on.

id=[i for i in range(10)]  # id=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def root(j): 
    print("Now j is %s, id[j] is %s" %(j, id[j]))
    while j != id[j]:
        print(" j != id[j]" ) # when this line is printed out, you will know that the while condition is true.
        print(j) 
        j=id[j] 
    print("j is printed as %s" %j ) # change return to print, it's easier to see the final result.
    print()

for k in range(len(id)):
    root(k)    

Run the code, you will get a result like this:

Now j is 0, id[j] is 0
j is printed as 0

Now j is 1, id[j] is 1
j is printed as 1

Now j is 2, id[j] is 2
j is printed as 2

Now j is 3, id[j] is 3
j is printed as 3

Now j is 4, id[j] is 4
j is printed as 4

Now j is 5, id[j] is 5
j is printed as 5

Now j is 6, id[j] is 6
j is printed as 6

Now j is 7, id[j] is 7
j is printed as 7

Now j is 8, id[j] is 8
j is printed as 8

Now j is 9, id[j] is 9
j is printed as 9