Why doesn't my code work how I expected?

I don’t understand why my code does not work. I figured out that if I modify lst in a for loop, then I would be in for trouble. So I created another list, tmp_lst = lst, and then do the for loop on tmp_lst and modify lst by popping the first even numbers. But it seems that when I pop something out of lst, it pops it also out of tmp_lst!!! This does not make any sense to me. Why does it operate on both lists!

Here’s the code:

def delete_starting_evens(lst):
tmp_lst = lst
for i in tmp_lst:
if len(lst) == 0:
return
if lst[0] % 2 == 0:
if len(lst)==1:
return
lst.pop(0)
else:
return lst

Hello @cedichou. Welcome to the forum.

There are several issues here.

When you assign lst to another variable name tmp_lst you are assigning the same exact list another name, so you now have two names that point to the same list. When you change the list, it doesn’t matter which name you use to make the change or to retrieve the list. Both names refer to the same list of elements/values. Hopefully that part made sense. If you want a copy of a list that won’t refer to the same list as the original, you can use slice like so: tmp_lst = lst[:]. That will give you a copy of the list instead of assigning another name to the same list.
Second, using the pop() method inside a for ... in loop will not work the way you want it to. When you pop() the first element from the list, the remaining elements will shift over, so your for ... in loop will skip the next element in line.
Third, please use the </> button from the menu bar to post your code, so we don’t have to guess at how it is indented. Go to a blank line, click the </> button, and then paste your code in the space indicated.

There’s a lot of guesswork involved in trying to interpret your code.; Please post it in Python by making use of the </> icon that appears in the menu bar atop the text box when you open it to type.

1 Like

Thanks a lot! It’s very helpful.

As for the formatting, I had no idea, I’ll use the </> button next time.

Cheers.

1 Like