So I have two lists and I want to use .pop() to remove an item from ListA and then use .append() to add it to ListB. I've tried this, but as soon as I use .pop(), the .append() function takes one index after that.
Here is the code I have so far:
ListA = ['a', 'b', 'c', 'd', 'e']
ListB = []
ListA.pop()
ListA.pop()
ListA.pop()
print 'ListA =', ListA
print 'ListB =', ListB
The output I get is:
ListA = ['a', 'b']
ListB = []
I would like the output to look like this:
ListA = ['a', 'b']
ListB = ['e', 'd', 'c']
I know I don't have any .append() functions, but when I put them in there I get an error. So that's the code working with just the .pop() function. I want to take the item that is being removed with .pop() and then append it to ListB.
Thanks for your help.
Pass the popped element to the append function:
a= ['a', 'b', 'c', 'd', 'e']
b= []
b.append(a.pop())
b.append(a.pop())
b.append(a.pop())
print 'ListA =', a
print 'ListB =', b
Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4 20090804 (release) 1] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> a = ['a','b','c']
>>> b = []
>>> b.append(a.pop())
>>> b.append(a.pop())
>>> b.append(a.pop())
>>> print "a =", a
a = []
>>> print "b =", b
b = ['c', 'b', 'a']
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With