Kyle Kim Kyle Kim - 4 years ago 88
Python Question

list manipulation error and append

I am a python beginner and have been having trouble understanding this code.

my_list = [12, "cat", 3.4, "dog", 62]
new_list = []

for k in range(5):

if k % 2:
m = my_list.pop(k)
new_list.append(m)

print(new_list)


As my understanding the result should be [12,62]
But it says ['cat',62]

Can anyone explain it to me?
It will be appreciated.

Answer Source

Well, what are the numbers in range(5)? 0, 1, 2, 3, 4, right?

Which of those are odd? (that is, k % 2 is nonzero and therefore "truthy") 1 and 3, right?

So, you first take item 1, "cat", and remove it from the original list and add it to the new list. The original list is now:

[12, 3.4, "dog", 62]

Now you take item 3, 62, and remove it from the original list and add it to the new list.

We have added "cat" and 62 to the new list, which started out empty. Therefore the new list is

["cat", 62]

The original list is:

[12, 3,4, "dog"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download