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.)
3 Answers 3
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]
It's because you pass your lists by reference. Compare with this assignment with copying
expon = list(seq[1])
coef = list(seq[0])
-
That`s just what I need! Thank you!Sean Xie– Sean Xie10/24/2015 11:57:35Commented Oct 24, 2015 at 11:57
-
it said 'TypeError: 'list' object is not callable'Sean Xie– Sean Xie10/24/2015 12:10:06Commented Oct 24, 2015 at 12:10
-
@SeanXie try my answer and let me knowm0bi5– m0bi510/24/2015 12:11:35Commented Oct 24, 2015 at 12:11
-
@SeanXie I checked it on both python 2 and python 3 and it works. Maybe you have object called 'list' in another part of your program? If it's true, just rename it.Yury– Yury10/24/2015 12:19:11Commented Oct 24, 2015 at 12:19
-
I just tried expon=list(polynom[0]) in python 3.5 console. It still said TypeErrorSean Xie– Sean Xie10/24/2015 12:22:52Commented Oct 24, 2015 at 12:22
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)
coeff
andexpon
are references to the same list objects asseq[0]
andseq[1]
.