+ 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?

29th Dec 2018, 6:44 PM
just trying to think
just trying to think - avatar
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.
29th Dec 2018, 6:53 PM
Anna
Anna - avatar
+ 2
Thanks!
29th Dec 2018, 6:55 PM
just trying to think
just trying to think - avatar
0
I don't get the whole of it but half of it, thank for this question SlavaLucker and answer Anna
30th Dec 2018, 8:18 AM
Alex K
Alex K - avatar