admin管理员组

文章数量:1356509

I was using pop function to catch a value and then add them as below

my_list = [1,2,3,4,5]  
a = my_list.pop(0)
b = my_list.pop(0)
c = a+b
print(c)

I was expecting the output as 2 but it shows it as 3. I tried capturing value at different position and add them but it always gave me a number higher then the actual answer

like if POP position were 1 and 2 the addition should be 5 but it shows 6.

Can someone help me with more clarity on this please?

I was using pop function to catch a value and then add them as below

my_list = [1,2,3,4,5]  
a = my_list.pop(0)
b = my_list.pop(0)
c = a+b
print(c)

I was expecting the output as 2 but it shows it as 3. I tried capturing value at different position and add them but it always gave me a number higher then the actual answer

like if POP position were 1 and 2 the addition should be 5 but it shows 6.

Can someone help me with more clarity on this please?

Share Improve this question edited Mar 27 at 21:09 Timur Shtatland 12.4k3 gold badges38 silver badges64 bronze badges asked Mar 27 at 20:50 mindbuzzzmindbuzzz 211 silver badge1 bronze badge 1
  • It helps to break the problem into smaller parts. You could introduce a print() after every line to see what the last line returned and what's in my_list. This way, you could quickly single out which line surprises you. – Friedrich Commented Mar 27 at 21:10
Add a comment  | 

1 Answer 1

Reset to default 3

I was expecting the output as 2 but it shows it as 3.

Keep in mind that pop() removes the element from the list. (At the specified index, which is 0 here.) So when you do this:

my_list = [1,2,3,4,5]
a = my_list.pop(0)

The a variable now has a value of 1. But my_list is now [2,3,4,5]. So when you do this:

b = my_list.pop(0)

Then b will have a value of 2, and now my_list will be [3,4,5].

The code is working correctly, the list is simply changing as it goes.


To achieve the behavior you're expecting, don't use pop(). Just reference the element in the list:

my_list = [1,2,3,4,5]  
a = my_list[0]
b = my_list[0]
c = a+b
print(c)

You can learn more about lists in Python here.

本文标签: pythonUse pop function to catch a value and then add themStack Overflow