pythonpython-3.2

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?


Solution

  • 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]