Search code examples
pythonrandom

How can I randomize existing byte array?


I create an array of bytes.

array = bytearray(random.randint(1, 8192))

# Now, how can I randomize array's elements?

Now how can I randomize each elements of the array?

Just like,

// with Java
var array = new byte[ThreadLocalRandom.current().nextInt(1, 8192)];
ThreadLocalRandom.current().nextBytes(array);

Solution

  • def randomize(array):
        array[:] = random.randbytes(len(array))
    

    Behaves like your answer's but is ~100 times faster. Time with an average-length array (4096 bytes):

      23.0 ±  0.3 μs  randomize_Kelly
    2191.5 ± 11.6 μs  randomize_Jin
    
    Python: 3.11.4 (main, Sep  9 2023, 15:09:21) [GCC 13.2.1 20230801]
    

    Attempt This Online!