0

I have a single large list and I want to append half the list to list1 and list2 while popping the items from the original list at the same time.

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
 
list1 = []
list2 = []

for item in mylist:
    list1.append(mylist.pop())
    list2.append(mylist.pop())

    
list1
[8, 6, 4]
list2
[7, 5, 3]

Why is it not going through the entire list in mylist? If I increase the list size by adding items it will also append/pop more items to the other lists, but still never completely goes through the entire list.

Again, I'm trying to get half the original list into list1 and the other half of the original list into list2.

George
  • 3
  • 1

1 Answers1

0

Modifying a list as you iterate over it tends to confuse the iteration.

Try this approach, where you're not iterating over the list itself:

>>> list1 = []
>>> list2 = []
>>> while mylist:
...     list1.append(mylist.pop())
...     list2.append(mylist.pop())
...
>>> list1
[8, 6, 4, 2]
>>> list2
[7, 5, 3, 1]

Or:

>>> mylist = [1, 2, 3, 4, 5, 6, 7, 8]
>>> list1 = mylist[::-2]
>>> list2 = mylist[-2::-2]
>>> list1
[8, 6, 4, 2]
>>> list2
[7, 5, 3, 1]
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Thank you. But why doesn't it work with a for loop? I don't understand why it isn't going all the way through the list. – George Dec 22 '21 at 01:35
  • See https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it The very brief explanation is that the `for` is trying to fetch the next index based on the length of the list from before you popped an item, so it fails and that kills the loop. – Samwise Dec 22 '21 at 15:52