Why doesn't the list in the for statement in Python get the items in order?

Asked 2 years ago, Updated 2 years ago, 14 views

#Write your function here
def delete_starting_evens(lst):
  lst_temp = lst
  print("--------------")
  print(lst,"lst")
  print(lst_temp,"lst_temp")
  for i in lst:
    print (i,"number")
    if i%2 ==0:
      print(i,"even")
      print(lst_temp.pop(0))
    else:
      print(i,"odd")
      break
  return lst_temp

#Uncomment the lines below when your function is done
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
print(delete_starting_evens([4, 8, 10]))
--Result--
[4, 8, 10, 11, 12, 15] lst
[4, 8, 10, 11, 12, 15] lst_temp
4 number
4 even
4
10 number
10 even
8
12 number
12 even
10
[11, 12, 15]
--------------
[4, 8, 10] lst
[4, 8, 10] lst_temp
4 number
4 even
4
10 number
10 even
8
[10]

If you turn the above code, [4, 8, 10, 11, 12, 15] lst will skip i directly from 4 to 10 instead of going to 4,8,10. It was lst_temp that ran pop(0). And 11 doesn't output 11 odds. I don't understand the code execution result as a whole, so what did I do wrong? Why?

python

2022-09-21 23:11

1 Answers

lst_temp = lst
The syntax is not to copy the lst list, but to copy the address of the list that lst has (somewhere in memory) to lst_temp.
(This is called a reference.))
Therefore, the operation of lst_temp is also visible in lst.
Now you know why that's happening, right?

So if you want to actually copy the list, not the address, you can use the methods below.

lst_temp = lst[:]
lst_temp = list(lst)


2022-09-21 23:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.