+ 2

Help understanding the answer to this python question

What does this for-loop do? Input: arr = [1, 2, 3, 4, 5, 6] i = 0 for _ in arr: del arr[i] i= i+1 print(arr) Answer: Deletes the elements in the even positions

7th May 2018, 2:51 PM
stephanie
stephanie - avatar
7 odpowiedzi
+ 3
iteration 1 -> i = 0 -> arr = [1,2,3,4,5,6] -> arr[0] = 1 -> del 1 -> arr = [2,3,4,5,6] iteration 2 -> i = 1 -> arr = [2,3,4,5,6] -> arr[1] = 3 -> del 3 -> arr = [2,4,5,6] iteration 3 -> i = 2 -> arr = [2,4,5,6] -> arr[2] = 5 -> del 5 -> arr = [2,4,6] Note: The meaning of "_" in Python is that it stores the last value in the interpreter. But the loop also runs fine if you use your classic "for x in arr:"
7th May 2018, 3:28 PM
Johannes
Johannes - avatar
+ 2
WeW confused me a bit nice one. here _ is iterating variable, arr is iterable object so at start of for loop _ holds value of 0 th index or 1st element then it deletes ith element as it's i=0 it deletes 1 now 2 is at 0 th index i is incremented by 1 so in next iteration _ has to hold value of 1st index element hence _ = 3 as now array starts with value 2 now i is 1 so delete statement will delete 3 and so on
7th May 2018, 3:14 PM
Yugabdh
Yugabdh - avatar
+ 2
Try this so what I said will sound a bit logical (._.") arr = [1, 2, 3, 4, 5, 6] i = 0 for _ in arr: print (_) del arr[i] i= i+1 print(arr)
7th May 2018, 3:17 PM
Yugabdh
Yugabdh - avatar
+ 1
this makes sense!! Thank you so much :)
7th May 2018, 3:20 PM
stephanie
stephanie - avatar
+ 1
Your questions are always so..tricky. I like to solve them always !!
7th May 2018, 3:22 PM
Yugabdh
Yugabdh - avatar
+ 1
thank you!! @johannes
7th May 2018, 3:31 PM
stephanie
stephanie - avatar
0
Great! There’s lots more where that came from lol
7th May 2018, 3:31 PM
stephanie
stephanie - avatar