TypeError: 'range' object does not support item assignment
Question:
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
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)))
if you can use numpy library you can replace range
with np.arange
:
import numpy as np
allocations = np.arange(len(people))
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
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)))
if you can use numpy library you can replace range
with np.arange
:
import numpy as np
allocations = np.arange(len(people))