+ 3
Can someone explain this code?
arr = [0, 1, 2, 3, 4, 5, 6] i = 0 for _ in arr: del arr[i] i = i + 1 print(arr) Why does this code print odd numbers?
3 Respuestas
+ 9
First the list is [0, 1, 2, 3, 4, 5, 6].
In the first iteration, the first element (arr[0]) is deleted, which is 0. Now the list is [1, 2, 3, 4, 5, 6].
Then, from the updated (!) list, the second element is deleted, which is 2. Now the list is [1, 3, 4, 5, 6].
Then, the third element is deleted, which is 4 etc.
You'll end up with [1, 3, 5].
You can add
print('_:', _)
print('arr:', arr)
in the for loop to understand better what it does.
+ 2
Thanks!
0
I don't get the whole of it but half of it, thank for this question SlavaLucker and answer Anna