Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why random.shuffle(list(range(n))) works, but random.shuffle(range(n)) does not?

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.

like image 979
A. Vaicenavicius Avatar asked Sep 17 '25 08:09

A. Vaicenavicius


1 Answers

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.

like image 182
sascha Avatar answered Sep 19 '25 03:09

sascha