Sean Xie
Sean Xie

Reputation: 1

Python: confused about assignment in nested lists

I put a polynomial in a nested list; for example 5X^3+4X^2+8X. I stored coefficients (5,4,8) in first list and exponents(3,2,1) in second:

polynom = [[5,4,8],[3,2,0]]

Then I define a function to pop the last term of coefficients and exponents like this

def expon_coef_pop(seq):
    expon = seq[1]
    coef = seq[0]
    expon.pop()
    coef.pop()
    return coef, expon

print(expon_coef_pop(polynom))
print(polynom)

# polynom changed into [[5,4],[4,2]]

Surprisingly, I found the value of polynom turned into [[5,4],[3,2]]. I thought I just modified value of expon and coef.

I don't want to change the value of polynomial.

How could this happen, and how to deal with this problem? I am confused about why the polynorm changed not the function. (I just wrote the function for a simple example.)

Upvotes: 0

Views: 87

Answers (3)

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

Just change simple modification. You can try it:

you need to Change

expon = seq[1] to expon = seq[1][:]
coef = seq[0] to coef = seq[0][:]

Your final code:

polynom = [[5,4,8],[3,2,0]]
def expon_coef_pop(seq):
    expon = seq[1][:]
    coef = seq[0][:]
    expon.pop()
    coef.pop()
    return coef, expon

print(expon_coef_pop(polynom))
print(polynom)

Upvotes: 0

bereal
bereal

Reputation: 34272

Both coef and expon are references pointing at the same list objects as seq[0] and seq[1] correspondingly. You will need to copy the lists before popping from them, which can also be done all in one step:

def expon_coef_pop(seq):
    return seq[0][:-1], seq[1][:-1]

Upvotes: 1

Yury
Yury

Reputation: 116

It's because you pass your lists by reference. Compare with this assignment with copying

expon = list(seq[1])
coef = list(seq[0])

Upvotes: 0

Related Questions