+ 5

Why is the output 2? 🤔

a=[1,2,0,3,4] for x in range(len(a)): if x>4: print(a[-a[-1]]) Output 2 Having the answer but not understanding it is so frustrating 😄

4th Mar 2018, 6:02 PM
Yohann
2 Antworten
+ 4
Okay, this is a little confusing so I'll try to break it down to the best of my abilities. First, a list with the variable name a is declared. This list contains 5 elements, therefore having a length of 5. Below that, a for loop is entered. This loop declares a variable x and sets it to an initial value of 0. Next, it will make it increment progressively, running the statements within the block, until it reaches a value equal to the length of the list a, or 5. In the for block, an if statement is testing the value of x throughout the loop, and will only run if x is greater than 4. In the last iteration, because x would be equal to 5, the statements within the if statement is run. This is where it gets just a little confusing. Within the if statement, a print function is set to print the value of the element at the negative value of the element at the index of -1 of the list a. Let's go through this in reverse. The element at the index -1 in the list a is 4, as negative indexes start with the last element having an index of -1. Then, the program finds the element at the index of the negative value that we just got, making it find the element at the index -4. With that, by counting from the last element starting at -1 and moving down by one each time, you reach the second element of the list which is equal to 2 (4 is at the index -1, 3 is at the index -2, 0 is at the index -3, and 2 is at the index -4). Hope this helped!
4th Mar 2018, 6:49 PM
Faisal
Faisal - avatar
+ 1
That’s a perfect explanation. Thank you very much!
4th Mar 2018, 7:57 PM
Yohann