I'm trying to transfer the contents of one list to another, but it's not working and I don't know why not. My code looks like this:
list1 = [1, 2, 3, 4, 5, 6]
list2 = []for item in list1:list2.append(item)list1.remove(item)
But if I run it my output looks like this:
>>> list1
[2, 4, 6]
>>> list2
[1, 3, 5]
My question is threefold, I guess: Why is this happening, how do I make it work, and am I overlooking an incredibly simple solution like a 'move' statement or something?
The reason is that you're (appending and) removing from the first list whereby it gets smaller. So the iterator stops before the whole list could be walked through.
To achieve what you want, do this:
list1 = [1, 2, 3, 4, 5, 6]
list2 = []# You couldn't just make 'list1_copy = list1',
# because this would just copy (share) the reference.
# (i.e. when you change list1_copy, list1 will also change)# this will make a (new) copy of list1
# so you can happily iterate over it ( without anything getting lost :)
list1_copy = list1[:]for item in list1_copy:list2.append(item)list1.remove(item)
The list1[start:end:step]
is the slicing syntax: when you leave start empty it defaults to 0, when you leave end empty it is the highest possible value. So list1[:] means everything in it. (thanks to Wallacoloo)
Like some dudes said, you could also use the extend
-method of the list
-object to just copy the one list to another, if this was your intention. (But I choosed the way above, because this is near to your approach.)
As you are new to python, I have something for you: Dive Into Python 3 - it's free and easy. - Have fun!