-1

What is the design reason behind having random.shuffle modify the list in-place, instead of returning a new one?

Given that, for instance, str.replace() return a new string, and could not be any other way given that strings are immutable, wouldn't it be more consistent if random.shuffle() returned a new list?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
robertspierre
  • 3,218
  • 2
  • 31
  • 46
  • I don't think a method on an immutable object, which as you say could not be any other way, is a good thing for a function that takes a mutable sequence to be consistent with. There are plenty of other Python methods and functions that operate in-place, the convention to be consistent with is that they all return `None`. As [the docs](https://docs.python.org/3/library/random.html#random.shuffle) say, you can use `sample(x, k=len(x))` as an alternative if you want a new shuffled list (or want to shuffle an immutable sequence like a tuple). – jonrsharpe Dec 16 '21 at 10:34

2 Answers2

1

When you have a (large) mutable container, it may be more efficient to modify it in-place instead of creating a new one. But is cannot be an option for immutable types like tuple or str.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

Most list- or array-shuffle implementations use Durstenfeld's variation of the Fisher-Yates algorithm (also known as "Algorithm P" in Knuth's Art of Computer Programming, vol. 2, section 3.4.2). This algorithm has the advantage that it completes in O(n) time and requires O(1) additional memory (on top of the O(n) space that the existing list needs to begin with). This is significantly more efficient than let's say creating a new list in each step. Even in a purely functional environment, the library implementation might make an initial copy of the original list and then apply this (mutating) algorithm. This would not be purely functional under the hood, but entirely hidden from the calling code. Also, by making a one-time copy, the implementation can be easily converted from in-place modification to a more purely functional style. However, as other folks have pointed out, in line with other principles that are observed for a particular library, the designers may choose not to do so.

raner
  • 1,175
  • 1
  • 11
  • 21