When, in Python 3, using random
module random.shuffle(list(range(n)))
works, but random.shuffle(range(n))
does not.
Why is it so?
When I type type(range(n))
it returns range
.
Python 3's range
now returns an range-object (beeing an immutable sequence) and not a list (like Python 2)!
A range-object (besides other differences) does not support item assignment, which is the error you observe (probably):
File ".../random.py", line 272, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'range' object does not support item assignment
The line 272 is the pythonic-way of swapping two variables in python, which is a common operation in most shuffle algorithms (like Fisher-Yates).
The docs also mentions this (if you want to shuffle sequences):
To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead
So this will work (and is equivalent given the task of shuffling):
shuffled_list = random.sample(range(n), k=n)
Your approach of creating a list first is also fine, if you can afford the memory/time needed to do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With