0
Can someone please help me understand this code
fruits = [“apples”,”cherries”,”orange”,”banana”] for fruits[-1] in fruits: print(fruits[-1], end=“|”) The output is apples|cherries|orange|orange Can someone explain the step by step sequence of this code? How is banana removed from the list?
3 ответов
+ 5
on first iteration,
fruits[-1]="apples"
list looks like the following now,
["apples", "cherries", "or.. ", " apples"]
_________________________
On second iteration,
fruits[-1]="cherries"
List now looks like : ["apples", "cherries", "or.. ", " cherries"]
_________________________
On third iteration,
fruits[-1]="orange"
List now looks like : ["apples", "cherries", "or.. ", " orange"]
_________________________
On fourth iteration,
fruits[-1]="orange"
List now looks like : ["apples", "cherries", "or.. ", " orange"]
+ 3
An explanation upon Abhay 's comment:
Consider this:
for x in fruits:
In each iteration, x is equal to one item of "fruits". When we replace x with fruits[-1] (the last item), that item value also is assigned to fruits[-1]. So in the third iteration, fruits[-1] will be equal to the third item. and so on...
This question was intetesting to me, so I searched a bit, and found this:
https://www.sololearn.com/discuss/2293183/?ref=app
+ 1
Abhay Yes thank you bro!