Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'range' object does not support item assignment

I was looking at some python 2.x code and attempted to translate it to py 3.x but I'm stuck on this section. Could anyone clarify what is wrong?

import random  emails = {     "x": "[REDACTED]@hotmail.com",     "x2": "[REDACTED]@hotmail.com",     "x3": "[REDACTED]@hotmail.com" }  people = emails.keys()  #generate a number for everyone allocations = range(len(people)) random.shuffle(allocations) 

This was the error given:

TypeError: 'range' object does not support item assignment 
like image 496
user2840982 Avatar asked Dec 10 '13 01:12

user2840982


People also ask

How do I fix TypeError int object does not support item assignment?

The Python "TypeError: 'int' object does not support item assignment" occurs when we try to assign a value to an integer using square brackets. To solve the error, correct the assignment or the accessor, as we can't mutate an integer value.

Which object does not support item assignment in Python?

The Python "TypeError: 'type' object does not support item assignment" occurs when we assign a data type to a variable and use square brackets to change an index or a key. To solve the error, set the variable to a mutable container object, e.g. my_list = [] .

How do you fix TypeError tuple object does not support item assignment?

The Python "TypeError: 'tuple' object does not support item assignment" occurs when we try to change the value of an item in a tuple. To solve the error, convert the tuple to a list, change the item at the specific index and convert the list back to a tuple.

How do I fix str object does not support item assignment in Python?

The Python "TypeError: 'str' object does not support item assignment" occurs when we try to modify a character in a string. Strings are immutable in Python, so we have to convert the string to a list, replace the list item and join the list elements into a string.


1 Answers

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))) 
like image 120
Tim Avatar answered Oct 11 '22 15:10

Tim