educative.io

Need to understand line 15

Why does the loop move on to the 2nd elm at the end of the first iteration for the while loop, instead of to the next line where index2 is now 5 and is the length of the list?

because it will add to the second index making it more than the value of the lenght of the array causing the for loop to move to the next elm

1 Like

Hello @Taiwo_Akinnusoye
Thanks for reaching out to us. Unfortunately, you misunderstood the code. Let’s take an example for better clarity:
Lets assume a list having elements : 9 4 9 6 4 and len(list) = 5 → total number of elements in the list
We have two variables index1 and index2 both are 0 initially.

  • First Iteration of outer loop index1= 0 < 5 condition becomes true , enter in the body of for loop.
    • index2 = 0 < 5 condition becomes true, enter in the body of while loop now checks if condition (index1 and index2 are equal in this case because both are 0) it means if condition false, now index2 increments then again go to while loop.
    • index2 = 1 < 5 condition becomes true, enter in the body of while loop now checks if condition (index1 and index2 are not equal in this case because index1 still 0 and index2 is 1 now, second if condition becomes false because list[0] is not equal to list[1] ) it means if condition false, now index2 increments then again go to while loop.
    • index2 = 2 < 5 condition becomes true, enter in the body of while loop now checks if condition (index1 and index2 are not equal in this case because index1 still 0 and index2 is 2 now, second if condition becomes true because list[0] is equal to list[2] ) it means if condition true so break the while loop and then go back to for loop and now we will do the second iteration.
  • Second Iteration of outer loop index1= 1 < 5 condition becomes true, enter in the body of for loop
    • index2 = 0 < 5 condition becomes true, enter in the body of while loop now checks if condition (index1 and index2 are not equal in this case because index1 is 1 and index2 is 0 now, second if condition becomes false because list[1] is not equal to list[0] ) it means if condition false, now index2 increments then again go to while loop.
    • index2 = 1 < 5 condition becomes true, enter in the body of while loop now checks if condition (index1 and index2 are equal in this case because index1 is 1 and index2 is also 1 now, so do not need to check second if condition because 1st condition is false. Now index2 increments then again go to while loop.
    • index2 = 2 < 5 and so on .

It means the outer loop picks elements one by one and the inner loop checks if the element is present more than once or not. Last if condition only executes when the outer loop (for loop) ends in the case of index1=5.

Hope it will help , Happy Learning :blush: