Can someone please help me understand this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

22nd Sep 2021, 11:10 PM
Jenkins
3 Answers
+ 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"]
22nd Sep 2021, 11:47 PM
Abhay
Abhay - avatar
+ 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
23rd Sep 2021, 1:03 AM
Arsalan [Inactive]
Arsalan [Inactive] - avatar
+ 1
Abhay Yes thank you bro!
29th Sep 2021, 3:58 PM
Jenkins