Reputation: 673
I have the following code:
def steps(low, hi, n):
rn = range(n)
newrn = rn
print rn #print 1
for x in rn[:]:
print x
newrn[x] = float(x)/n
diff = hi - low
print newrn
print rn #print 2
for y in rn[:]:
print y
rn.insert(y, (newrn[y] * diff) + low)
return rn
for some reason, my first print of rn returns [0, 1, 2] but my second print returns [0, .333, .666]. Why is rn changing? I only change newrn, but rn is getting changed as well. This is making me get a 'list indices must be integer not float' error when it tries to run the rn.insert line.
any help?
Upvotes: 0
Views: 237
Reputation: 3165
This is how variables work in python. In there:
newrn = rn
You're assigning a reference, not a value (which is good sometimes, since you don't copy all the values to a new list). If you want a new, separate list with the same values, do this:
newrn = list(rn)
Upvotes: 3
Reputation: 34655
The problem is when you made this assignment: newrn = rn
. Now both newrn
and rn
point to the same list, so when you modify one, you modify both.
Use newrn = rn[:]
instead.
Upvotes: 5