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] = [] 

Track. I get a weird error:

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

Not sure why it throws this exception, do they change something in Python 3.2?

+4
source share
2 answers

Guess: they changed something. The range used to return the list, and now it returns an object with an iterable range, very similar to the old xrange.

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

You can get a single item, but not assign it, because this is 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 the list on a range object to get what you are 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] 
+6
source

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)] 
+2
source

Source: https://habr.com/ru/post/1394121/


All Articles