+ 8
For loop
I was flicking through some quiz suggestions and came across this piece of code: x=[1,3,5,7] for x[-1] in x: print(x[-1], end=' '). # output: 1 3 5 5 Would someone explain what is happening to produce this output, as I've never seen a for loop done like this before? Thanks
8 odpowiedzi
+ 4
-1 index means the last item in the list. So, for is looping around the list through it's last item. At the last iteration it places the last value to itself. It is not changed and stores previous value -5.
+ 5
I think I understand now. So, during each iteration, the list actually gets changed?
In first iteration, x[-1] => 1, so x is now [1,3,5,1], right? Then by the third iteration, x has become [1,3,5,5], so then during the last iteration, x[-1] is being reassigned to itself, hence it doesn't change.
Thanks for taking the time to explain.
Is there any particular situation where this approach would be useful?
+ 3
Thanks for the explanation Sergey Ushakov but it just isn't sinking in for me.
I understand that x[-1] is the last item in x, but I don't understand what it means to loop around the list "through its last item". Could you break it down any further, please?
I'm sure I'm being stupid but I just can't get my head arounf it.
+ 3
No worries. Thank you!
+ 2
It means that for places each value of x into x[-1] one by one, including x[-1]
+ 1
yes, you right.
I don't know the answer to the second question.
0
i cannot undrr stand the question of for loop in thecourse ofpython language
0
I think I know it.
"x=[1,3,5,7]" -> x is a list, lengh =4.
"for x[-1] in x" -> This is to replace the x[-1] with the values of x.
x[-1] means the last one in the list. Therefore we will see the only change in the last value of x list.
So what to replace the last value of x list?
We need to look step by step of the look:
At the begining, the x is [1,3,5,7]
The 1st run: replace the new x[-1] with the x[0]. Now, the x becomes [1,3,5,1]
The 2nd run: replace the new x[-1] with the x[1] of the new x. Then, the x becomes [1,3,5,3]
The 3rd run: replace the new x[-1] with the x[2] of the x from the last step. Now, the x becomes [1,3,5,5]
The 4th run: replace the new x[-1] with the x[3] of the x from the last step. Yes, the x[3] is 5. Therefore the x becomes [1,3,5,5]
The lengh of x is 4, therefore run four times in the loop.
The x is updated after each run. I think it is the point to get it.
"print(x[-1])" -> means to print only the x[-1], the last value of x, of each x.
So we can see from the listed x above and find the output is...
=> 1 3 5 5