fahimabid07
fahimabid07

Reputation: 43

Unexpected result while executing list.pop()?

I'm trying to assign a = x and b = x.pop(); Albeit I'm getting unexpected assignments. Could you explain this?

>>> x = [10, 11, 12, 13]
>>> a, b = x, x.pop(2)
>>> print a
[10, 11, 13] # Shouldn't I get a = [10, 11, 12, 13]?
>>> print b
12

Upvotes: 3

Views: 96

Answers (3)

Narendra
Narendra

Reputation: 1529

Since you're referring direct list, it's popping and assigning what left in list. If you have list as copy then try this:-

x = [10, 11, 12, 13]
a,b = x.copy(),x.pop(2)
print(a) # your expected output

Upvotes: 4

Nick_4810
Nick_4810

Reputation: 1

When you say a=x, both a and x are pointing to the same list, therefore modifying a will also modify x. If you say a=list(x) then a will be a separate copy of the list x.

Upvotes: 0

vrndandu
vrndandu

Reputation: 16

You will get a = [10,11,13], b = 12.

A value of x pops out after you execute 'b = x.pop()' and x changes forever i.e for the rest of the program after executing value 'b'

Upvotes: 0

Related Questions