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 |1 Answer
Reset to default 3I 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
版权声明:本文标题:python - Use pop function to catch a value and then add them - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744068539a2585461.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
print()
after every line to see what the last line returned and what's inmy_list
. This way, you could quickly single out which line surprises you. – Friedrich Commented Mar 27 at 21:10