Typeerror: 'Range' Object Does Not Support Item Assignment

TypeError: 'range' object does not support item assignment

In Python 3, range returns a lazy sequence object - it does not return a list. There is no way to rearrange elements in a range object, so it cannot be shuffled.

Convert it to a list before shuffling.

allocations = list(range(len(people)))

range' object does not support item assignment in python3

range object can not be set.

You can change it to list by:

 xr = list(range(6)); yr = list(range(6));  

But I don't understand why you use in range in the first place. If you just wan to initialize a list, I would go with something like:

xr,  yr = 6*[None], 6*[None]

Ofcourse you can put 0 or whatever instead None

random.shuffle(range(10)) report TypeError

random.shuffle shuffles the given sequence, in-place, so it cannot be an immutable iterable, such as range. You need to provide a list.

The recommended way to fix your code is to create a list out of your range, by passing it to the list type constructor, i.e. list(range(10)).

num_arr = list(range(10))
random.shuffle(num_arr)

Another (and not so common) way to do it would be to use list comprehension:

num_arr = [n for n in range(10)]
random.shuffle(num_arr)

However, note that using list constructor could be much faster than using list comprehension

i am working to create a function but this code appears TypeError: 'int' object does not support item assignment

couple of issues in your code

  1. your code is not returning any value , so T is not defined outside of function
  2. n[i] meant to be T[i]
  3. you need to change the range to n+1
  4. you can shorten/optimize your code as follows

so:

def num():
while True:
n= int(input("donnez le num"))
if n > 0:
break
return [i for i in range(0,n+1)]

print(num())

et voila, output:

donnez le num 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

TypeError: 'str' object does not support item assignment in iteration

Without knowing too much on what you are trying to achieve, i can explain the error.

As you define it at line 10, data is a dictionary (notice the dict()). When looping over a dictionary in python, you loop over its keys.

So when you loop using for t in data, the vairable t contains just a key, the data type of which is str. On the next line you try to add an item to t as if it were a dict. But str objects don't support this, hence the error.

If your intention was to loop over the keys and values in the dict data you can use for key, value in data.items(): and then use value for further processing.



Related Topics



Leave a reply



Submit