Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange error with range type in list assignment

r = range(10) 

for j in range(maxj):
    # get ith number from r...       
    i = randint(1,m)
    n = r[i]
    # remove it from r...
    r[i:i+1] = []

The traceback I am getting a strange error:

r[i:i+1] = []
TypeError: 'range' object does not support item assignment

Not sure why it is throwing this exception, did they change something in Python 3.2?

like image 363
zacharoni16 Avatar asked Feb 01 '12 05:02

zacharoni16


2 Answers

Good guess: they did change something. Range used to return a list, and now it returns an iterable range object, very much like the old xrange.

>>> range(10)
range(0, 10)

You can get an individual element but not assign to it, because it's not a list:

>>> range(10)[5]
5
>>> r = range(10)
>>> r[:3] = []
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    r[:3] = []
TypeError: 'range' object does not support item assignment

You can simply call list on the range object to get what you're used to:

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> r = list(range(10))
>>> r[:3] = [2,3,4]
>>> r
[2, 3, 4, 3, 4, 5, 6, 7, 8, 9]
like image 177
DSM Avatar answered Oct 09 '22 10:10

DSM


Try this for a fix (I'm not an expert on python 3.0 - just speculating at this point)

r = [i for i in range(maxj)]
like image 2
inspectorG4dget Avatar answered Oct 09 '22 11:10

inspectorG4dget