-2

I want that for loop iterates the number of times, there are items in my_list, and correspondingly during each execution pops the items out of my_list and add them in purchase_list, until all the elements of my_list are popped and appended into the purchase_list. But it doesn't happen. Why?

my_list = ['pen' , 'pencil' , 'cell phone' , 'axiom team' , 'panacloud' ]
purchase_list = []
for items in my_list:
    purchase_item = my_list.pop()
    purchase_list.append(purchase_item)

print(purchase_list)

Output is as follows:

['panacloud', 'axiom team', 'cell phone']
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76

2 Answers2

1

Do not pop while iterating through list.

If you are looking to empty one list and fill another, use:

my_list = ['pen' , 'pencil' , 'cell phone' , 'axiom team' , 'panacloud' ]

purchase_list = my_list  # ['pen', 'pencil', 'cell phone', 'axiom team', 'panacloud']
my_list = []             # []
Austin
  • 25,759
  • 4
  • 25
  • 48
1

Your question is why your code is not working. Well popping the element is never a good idea in Python during the iteration. While iterating and popping you are actually iterating from the front while removing(shrinking) your list(from rear) in the same loop. That is the reason loop executed three times as other elements were removed with earlier two iterations.

Why not just reversing the list and creating a new list ?

new_list = list(reversed(my_list))

If you want your new_list to be emptied

new_list =[]

OR if you want to delete

del my_list
mad_
  • 8,121
  • 2
  • 25
  • 40