Copy>>> import os
>>> "\x00"+os.urandom(4)+"\x00"
'\x00!\xc0zK\x00'
Answer from John La Rooy on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › random.html
random — Generate pseudo-random numbers
February 23, 2026 - For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.
🌐
Tutorialspoint
tutorialspoint.com › python › python_random_randbytes_method.htm
Python random.randbytes() Function
Let's look at an example of how to use the Python random.randbytes() function to generate 8 random bytes.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-generate-random-bytes
Generate random bytes or random Hex string in Python | bobbyhadz
April 10, 2024 - The random.choices method returns a k sized list of elements chosen from the provided iterable with replacement. ... Copied!import random # 👇️ ['9', 'A', 'C', 'C', '2', 'C'] print(random.choices('0123456789ABCDEF', k=6)) With replacement basically means that the same element can be returned multiple times. The random.choices() method was introduced in Python 3.9.
🌐
Educative
educative.io › answers › what-is-the-randomrandbytes-method-in-python
What is the random.randbytes() method in Python?
The randbytes method of the random module is used to generate bytes of the given size. This method was introduced in Python (version 3.9).
🌐
GitHub
github.com › python › cpython › blob › main › Lib › random.py
cpython/Lib/random.py at main · python/cpython
"randbytes", "randint", "random", "randrange", "sample", "seed", "setstate", "shuffle", "triangular", "uniform", "vonmisesvariate", "weibullvariate", ] · NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2.0) ...
Author   python
🌐
DEV Community
dev.to › izaan › generate-random-bytes-of-size-n-in-python-3-9-bm4
Generate random bytes of size n in Python 3.9 - DEV Community
August 14, 2021 - Python version 3.9 introduced the new function, randbytes(n) which returns bytes of size "n".
🌐
Interactive Chaos
interactivechaos.com › en › python › function › randomrandbytes
random.randbytes | Interactive Chaos
Python scenarios · Full name · random.randbytes · Library · random · Syntax · random.randbytes(n) Description · The random.randbytes function generates random bytes. Parameters · n: Number of bytes to generate. Result · The random.randbytes function returns a value of type bytes .
Find elsewhere
🌐
GitLab
gdevops.gitlab.io › tuto_python › versions › 3.9.0 › random › random.html
Python 3.9 Feature Random Bytes Generation
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify ...
🌐
Programming Idioms
programming-idioms.org › idiom › 310 › fill-array-with-random-bytes › 5790 › python
Fill array with random bytes, in Python
Created a zeroed list of integers · Random string · Cheatsheets · Issues · Report a bug · × · Python · a[:] = random.randbytes(len(a)) Python · a = random.randbytes(N) Fortran · real, dimension(100) :: b integer(int8), dimension(100) :: a call random_number(b) a = b*256 - 128 ·
🌐
Python
bugs.python.org › issue40286
Issue 40286: Add randbytes() method to random.Random - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/84466
🌐
Learn By Example
learnbyexample.org › python-random-randbytes-method
Python Random randbytes() Method - Learn By Example
April 23, 2024 - Learn in detail about Python's random.randbytes() method, including its usage, syntax, parameters, examples, and important points to note.
🌐
Linux Tip
linuxscrew.com › home › programming › python › how to generate random numbers and strings in python
How to Generate Random Numbers and Strings in Python
September 20, 2021 - From Python version 3.9, the randbytes() function can be used to generate a series of random bytes of a given length – this can then be used as a randomized string.
🌐
NumPy
numpy.org › doc › stable › reference › random › generated › numpy.random.bytes.html
numpy.random.bytes — NumPy v2.4 Manual
Return random bytes · New code should use the bytes method of a Generator instance instead; please see the Quick start
🌐
GitHub
gist.github.com › rusek › c9d07140f61851693dfd
Random bytes generation in Python · GitHub
Random bytes generation in Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Gemfury
gemfury.com › hemamaps › twisted
python/randbytes.py · hemamaps / Twisted v16.3.0 - python package | Gemfury
Why Gemfury? Push, build, and install RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages ... # -*- test-case-name: twisted.test.test_randbytes -*- # Copyright (c) Twisted Matrix Laboratories.
Version   16.3.0
Author   hemamaps
🌐
GeeksforGeeks
geeksforgeeks.org › random-getrandbits-in-python
random.getrandbits() in Python | GeeksforGeeks
June 14, 2022 - The choices() method returns multiple random elements from the list with replacement. Unlike random.choice(), which selects a single item, random.choices() allows us to select multiple items making it particularly useful for tasks like sampling from a population or generating random data.Example:Pyt ... sample() is an built-in function of random module in Python that returns a particular length list of items chosen from the sequence i.e.
🌐
HotExamples
python.hotexamples.com › examples › util › - › randbytes › python-randbytes-function-examples.html
Python randbytes Examples, util.randbytes Python Examples - HotExamples
randcount = random.randint(16, 32) prefix = util.randbytes(randcount) cipher = AES.new(key, AES.MODE_ECB) s = util.padPKCS7(prefix + s + base64.b64decode(challenge12.encodedSuffix), 16) return cipher.encrypt(s)
Top answer
1 of 4
59

The os module provides urandom, even on Windows:

bytearray(os.urandom(1000000))

This seems to perform as quickly as you need, in fact, I get better timings than your numpy (though our machines could be wildly different):

timeit.timeit(lambda:bytearray(os.urandom(1000000)), number=10)
0.0554857286941
2 of 4
13

There are several possibilities, some faster than os.urandom. Also consider whether the data has to be generated deterministically from a random seed. This is invaluable for unit tests where failures have to be reproducible.

short and pithy:

lambda n:bytearray(map(random.getrandbits,(8,)*n))

I've use the above for unit tests and it was fast enough but can it be done faster?

using itertools:

lambda n:bytearray(itertools.imap(random.getrandbits,itertools.repeat(8,n))))

itertools and struct producing 8 bytes per iteration

lambda n:(b''.join(map(struct.Struct("!Q").pack,itertools.imap(
    random.getrandbits,itertools.repeat(64,(n+7)//8)))))[:n]

Anything based on b''.join will fill 3-7x the memory consumed by the final bytearray with temporary objects since it queues up all the sub-strings before joining them together and python objects have lots of storage overhead.

Producing large chunks with a specialized function gives better performance and avoids filling memory.

import random,itertools,struct,operator
def randbytes(n,_struct8k=struct.Struct("!1000Q").pack_into):
    if n<8000:
        longs=(n+7)//8
        return struct.pack("!%iQ"%longs,*map(
            random.getrandbits,itertools.repeat(64,longs)))[:n]
    data=bytearray(n);
    for offset in xrange(0,n-7999,8000):
        _struct8k(data,offset,
            *map(random.getrandbits,itertools.repeat(64,1000)))
    offset+=8000
    data[offset:]=randbytes(n-offset)
    return data

Performance

  • .84 MB/s :original solution with randint:
  • 4.8 MB/s :bytearray(getrandbits(8) for _ in xrange(n)): (solution by other poster)
  • 6.4MB/s :bytearray(map(getrandbits,(8,)*n))
  • 7.2 MB/s :itertools and getrandbits
  • 10 MB/s :os.urandom
  • 23 MB/s :itertools and struct
  • 35 MB/s :optimised function (holds for len = 100MB ... 1KB)

Note:all tests used 10KB as the string size. Results were consistent up till intermediate results filled memory.

Note:os.urandom is meant to provide secure random seeds. Applications expand that seed with their own fast PRNG. Here's an example, using AES in counter mode as a PRNG:

import os
seed=os.urandom(32)

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
backend = default_backend()
cipher = Cipher(algorithms.AES(seed), modes.CTR(b'\0'*16), backend=backend)
encryptor = cipher.encryptor()

nulls=b'\0'*(10**5) #100k
from timeit import timeit
t=timeit(lambda:encryptor.update(nulls),number=10**5) #1GB, (100K*10k)
print("%.1f MB/s"%(1000/t))

This produces pseudorandom data at 180 MB/s. (no hardware AES acceleration, single core) That's only ~5x the speed of the pure python code above.

Addendum

There's a pure python crypto library waiting to be written. Putting the above techniques together with hashlib and stream cipher techniques looks promising. Here's a teaser, a fast string xor (42MB/s).

def xor(a,b):
    s="!%iQ%iB"%divmod(len(a),8)
    return struct.pack(s,*itertools.imap(operator.xor,
        struct.unpack(s,a),
        struct.unpack(s,b)))