PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Random » Python random randrange() and randint() to generate random integer number within a range

Python random randrange() and randint() to generate random integer number within a range

Updated on: October 1, 2022 | 18 Comments

In this lesson, we will see how to use the randrange() and randint() functions of a Python random module to generate a random integer number.

Using randrange() and randint() functions of a random module, we can generate a random integer within a range. In this lesson, you’ll learn the following functions to generate random numbers in Python. We will see each one of them with examples.

FunctionDescription
random.randint(0, 9)Returns any random integer from 0 to 9
random.randrange(20)Returns a random integer from 0 to 19
random.randrange(2, 20)Returns a random integer from 2 to 19.
random.randrange(100, 1000, 3)Returns any random integer from 100 to 999 with step 3. For example, any number from 100, 103, 106 … 994, 997.
random.randrange(-50, -5)Returns a random negative integer between -50 to -6.
random.sample(range(0, 1000), 10)Returns a list of random numbers
secrets.randbelow(10)Returns a secure random number
functions to generate random numbers

Also, See:

  • Python random data generation Exercise
  • Python random data generation Quiz

Table of contents

  • How to use random.randint()
    • random.randint() example of generating random number
  • random.randrange() to generate random integers within a range
    • Syntax
    • random.randrange() examples
    • Random number of a specific length
      • Random integer number multiple of n
  • Random negative integer
    • Generate random positive or negative integer
    • Randomly generate 1 or -1
  • Generate a list of random integer numbers
    • Create a list of random numbers without duplicates
    • Sort random numbers list
  • Generate a secure random integer
  • Create a multidimensional array of random integers
  • Points to remember about randint() and randrange()
  • Next Steps

How to use random.randint()

Syntax:

random.randint(start, stop)Code language: Python (python)

This function returns a random integer between a given start and stop integer.

Parameters:

It takes two parameters. Both are mandatory.

  • start: It is the start position of a range. The default value is 0 if not specified.
  • stop: It is the end position of a range.

Return value:

It will generate any random integer number from the inclusive range. The randint(start, stop) consider both the start and stop numbers while generating random integers

How to use Python randint() and randrange() to get random integers

  1. Import random module

    Use Python’s random module to work with random data generation.
    import it using a import random statement.

  2. Use randint() Generate random integer

    Use a random.randint() function to get a random integer number from the inclusive range. For example, random.randint(0, 10) will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].

  3. Use the randrnage() function to generate a random integer within a range

    Use a random.randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random.randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).

random.randint() example of generating random number

import random

# random integer from 0 to 9
num1 = random.randint(0, 9)
print(num1)
# output 5

# Random integer from 10 to 100
num2 = random.randint(10, 100)
print(num2)
# Output 84Code language: Python (python)

Note: You cannot use float numbers in randint(). It will raise a ValueError ( non-integer stop for randrange()) if you use non-integer numbers. Please, read how to generate a random float number within a range.

random.randrange() to generate random integers within a range

Now let’s see how to use the random.randrange() function to get a random integer number from the given exclusive range by specifying the increment.

Syntax

random.randrange(start, stop[, step])Code language: Python (python)

This function returns a random integer from a range(start, stop, step). For example, random.randrange(0, 10, 2) will generate any random numbers from [0, 2, 4, 6, 8].

Parameters

It takes three parameters. Out of three, two parameters are optional. i.e., start and step are optional.

  • start: it is the star number in a range. i.e., lower limit. The default value is 0 if not specified.
  • stop: It is the end/last number in a range. It is the upper limit.
  • step: Specify the increment value in range. The generated random number is divisible by step. The default value is 1 if not specified.

random.randrange() examples

In the following example, we are trying to print a random int in a given range. This example demonstrates all the variants of random.randrange() function.

import random

# random integer from 0 to 9
num1 = random.randint(0, 9)
print(num1)
# output 5

# Random integer from 10 to 100
num2 = random.randint(10, 100)
print(num2)
# Output 84Code language: Python (python)

Note:

  • The randrange() doesn’t consider the stop number while generating a random integer. It is an exclusive random range. For example, randrange(2, 20, 2) will return any random number between 2 to 20, such as 2, 4, 6, …18. It will never select 20.
  • Same as randint(), you cannot use float value in randrange() too. It will raise a ValueError (non-integer arg 1 for randrange()) if you use non-integers.

Random number of a specific length

Let’s see how to generate a random number of length n. For example, any random number of length four, such as 7523, 3674. We can accomplish this using both randint() randrange().

import random

# random number of length 4
num1 = random.randint(1000, 9999)
# random number of length 4 with step 2

num2 = random.randrange(1000, 10000, 2)
print(num1, num2)

# Output 3457 5116
Code language: Python (python)

Note: As you can see, we set a start = 1000 and a stop = 10000 because we want to generate the random number of length 4 (from 1000 to 9999).

Random integer number multiple of n

For example, let’s generate a random number between x and y multiple of 3 like 3, 6, 39, 66.

import random

num = random.randrange(3, 300, 3)
print(num)
# output 144Code language: Python (python)

Random negative integer

Let’s see how to generate a random negative integer between -60 to -6.

import random

singed_int = random.randrange(-60, -6)
print(singed_int)
# Output -16Code language: Python (python)

Generate random positive or negative integer

import random

for i in range(5):
    print(random.randint(-10, 10), end=' ')
# Output 10 -1 5 -10 -7Code language: Python (python)

Randomly generate 1 or -1

import random

num = random.choice([-1, 1])
print(num)Code language: Python (python)

Note: we used random.choice() to choose a single number from the list of numbers. Here our list is [-1, 1].

Generate a list of random integer numbers

In this section, we will see how to generate multiple random numbers. Sometimes we need a sample list to perform testing. In this case, instead of creating it manually, we can create a list with random integers using a randint() or randrange(). In this example, we will see how to create a list of 10 random integers.

import random

random_list = []
# Set a length of the list to 10
for i in range(0, 10):
    # any random numbers from 0 to 1000
    random_list.append(random.randint(0, 1000))
print(random_list)
# Output [994, 287, 65, 994, 936, 462, 839, 160, 689, 624]Code language: Python (python)

Create a list of random numbers without duplicates

Note: In the above example, there is a chance of occurring a duplicate number in a list.

If you want to make sure each number in the list is unique, use the random.sample() method to generate a list of unique random numbers.

  • The sample() returns a sampled list of selected random numbers within a range of values.
  • It never repeats the element so that we can get a list of random numbers without duplicates
import random

# Generate 10 unique random numbers within a range
num_list = random.sample(range(0, 1000), 10)
print(num_list)
# Output [499, 580, 735, 784, 574, 511, 704, 637, 472, 211]Code language: Python (python)

Note: You can also use the step parameter of the range() function to specify the increment. For example, you want a list of 10 random numbers, but each integer in a list must be divisible by 5, then use random.sample(range(0, 1000, 5), 10)

Sort random numbers list

Use the sort() function to sort a list of random integers in ascending order

import random

sample_list = random.sample(range(50, 500, 5), 5)
# Before sorting
print(sample_list)
# Output [305, 240, 260, 235, 445]

sample_list.sort()
# After sorting
print(sample_list)
# Output [235, 240, 260, 305, 445]
Code language: Python (python)

Generate a secure random integer

Above all, examples are not cryptographically secure. The cryptographically secure random generator generates random numbers using synchronization methods to ensure that no two processes can obtain the same number simultaneously.

If you are producing random numbers for a security-sensitive application, then you must use this approach.

Use the secrets module if you are using a Python version higher than 3.6.

import secrets

# secure random integer
# from 0 to 10
secure_num = secrets.randbelow(10)
print(secure_num)
# Output 5Code language: Python (python)

If you are using Python version less than 3.6, then use the random.SystemRandom().randint() or random.SystemRandom().randrange() functions.

Create a multidimensional array of random integers

Python’s NumPy module has a numpy.random package to generate random data. To create a random multidimensional array of integers within a given range, we can use the following NumPy methods:

  • randint()
  • random_integers()
  • np.randint(low[, high, size, dtype]) to get random integers array from low (inclusive) to high (exclusive).
  • np.random_integers(low[, high, size]) to get random integer’s array between low and high, inclusive.

Now, Let see the example.

Generate a 4 x 4 array of ints between 10 and 50, exclusive:

import numpy

# 4 x 4 array
newArray = numpy.random.randint(10, 50, size=(4, 4))
print(newArray)Code language: Python (python)

Output:

[[10 48 30 24]
 [13 46 30 11]
 [12 28 49 26]
 [30 18 49 35]]

Generate a 5 x 3 array of random integers between 60 and 100, inclusive.

import numpy

# 3 x 5 array of ints
newArray = numpy.random.random_integers(60, 100, size=(3, 5))
print(newArray)Code language: Python (python)

Output:

[[63 76 95 93 75]
 [71 84 63 99 93]
 [65 64 66 69 92]]

Points to remember about randint() and randrange()

  • Use randint() when you want to generate a random number from an inclusive range.
  • Use randrange() when you want to generate a random number within a range by specifying the increment. It produces a random number from an exclusive range.

You should be aware of some value constraints of a randrange() function.

  • The randint() rand randrange() works only with integers. You cannot use float numbers.
  • The step must not be 0. If it is set to 0, you will get a ValueError: zero step for randrange()
  • The start should not be greater than stop if you are using all positive numbers. If you set start greater than stop, you will get a ValueError: empty range for randrange()

Examples

import random

# ValueError: empty range for randrange()
print(random.randrange(100, 10, 2))Code language: Python (python)

But, you can also set a start value greater than stop if you are using a negative step value.

import random

print(random.randrange(100, 10, -2))
# output 60Code language: Python (python)

Next Steps

I want to hear from you. What do you think of this article on randint() and randrange()? Or maybe I missed one of the usages of those two functions. Either way, let me know by leaving a comment below.

Also, try to solve the following exercise and quiz to have a better understanding of working with random data in Python.

  • Python random data generation Exercise to practice and master the random data generation techniques in Python.
  • Python random data generation Quiz to test your random data generation concepts.

Filed Under: Python, Python Basics, Python Random

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Random

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Daniel says

    July 14, 2024 at 10:21 pm

    Nice work
    This
    import numpy

    # 3 x 5 array of ints
    newArray = numpy.random.random_integers(60, 100, size=(3, 5))
    print(newArray)

    Gives deprecationWarning warning on my pydriod3 on Android phone, although it stills works.
    Any idea?

    Reply
  2. Biswajit Sasmal says

    April 12, 2024 at 12:26 am

    In my opinion this website is awesome for beginners friendly from basics to advanced. I am looking for this kind of article to read more about python basics to advance in structured way learning. Finally, from the bottom of my heart thanks to you sir!

    Reply
  3. Dilli Ram Chaudhary says

    July 15, 2023 at 8:21 am

    Hey Vishal! Thanks a lot for this extensive source on random number for python. As you’ve said that in case you miss something to post on this site, I suggest you for the same to add about the random.seed().

    Reply
  4. Bryan (aka brewmanz) says

    September 21, 2022 at 6:48 am

    Your line
    random.randrange(100, 1000, 3) # Returns any random integer of length 3″
    is incorrect.
    This will only return possible numbers 100, 103, 106 … 994, 997.

    Reply
    • JurGraf says

      October 1, 2022 at 1:00 am

      Exactly! I was very surprised to see such an error in the table.

      Reply
      • Vishal says

        October 1, 2022 at 11:15 am

        Thank you, Bryan and JurGraf, for pointing out the mistake. I have updated the article with the correct description.

        Reply
  5. coco says

    September 5, 2021 at 4:50 pm

    I was wondering how to plot EHR data from longitudinal data? For example, pick patient A and plot its anxiety (column) over the past few months (multiple CSV files)? Any assistant would be greatly appreciated, thank you!

    Reply
  6. Akash Kumar says

    June 11, 2021 at 5:12 pm

    list_of_random = random.sample(range(0, 180), 10)
    Reply
  7. Johannes Riedinger says

    June 25, 2020 at 6:05 pm

    I would like to send you a short presentation as .pdf which covers a point you have totally missed about random.randrange. How can I get that to you?

    Reply
    • Vishal says

      June 29, 2020 at 12:48 pm

      Hey Johannes, You can email me on admin@pynative.com

      Reply
      • Hans Beauvoir says

        September 25, 2020 at 2:23 am

        Write a program that
        a. Generates 50,000 random numbers and puts them in an array.
        b. Sorts the numbers using any sorting technique (Selection sort is fine, but you can try another one). This should take a few minutes to run.
        c. Ask the user for a number between 0 and 20,000,000 and search for it in your sorted array using a simple linear search. Is this a good idea?
        d. Ask the user for a number between 0 and 20,000,000 and search for it in your sorted array using a binary search.

        Hint: To generate random numbers you need to include this module:
        import random
        To get a random number w :

        w = random.randint(0,20000000)
        This will give w a random value between 0 and 20,000,000

        Could you solve this program for me please right now?

        Reply
  8. Surbhi says

    June 23, 2020 at 3:20 am

    Very nice article and helpful.

    The start should not be greater than stop. If mistakenly you set start greater then stop you will get a ValueError: empty range for randrange()

    i have tried start value greater than stop value print(random.randrange(100,1,-2))
    it is working fine..juts have to use step value as negative …. please edit

    Reply
    • Vishal says

      June 25, 2020 at 3:15 pm

      Hey Surbhi, Thank you for your suggestion.

      Reply
  9. yup says

    May 12, 2020 at 12:22 am

    The comment…

    # Random number between 20 and 40

    … is misleading, as it will include 20 but NOT 40. I know you made this clear above, but for those skimming this could trip people up.

    Reply
    • Vishal says

      May 14, 2020 at 4:59 pm

      Thank you. I have updated the example

      Reply
      • Perison pako says

        June 4, 2020 at 8:03 pm

        Thanks. You have helped understand this topic

        Reply
  10. Giz says

    March 7, 2019 at 9:15 pm

    generate a random number of length 4:

    number  = random.randrange(1000, 9999)
    

    should be:

    number  = random.randrange(1000, 10000)
    
    Reply
    • Priyanka Pawar says

      December 6, 2019 at 1:02 pm

      import random
      print("Random number between 80 and 90 : ", random.randrange(80, 90))
      

      should be like,

      import random
      print("Random number between 80 and 90 : ", random.randrange(80, 90,0))
      

      Then only it will generate error

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics Python Random
TweetF  sharein  shareP  Pin

  Python Random Data

  • Guide to Generate Random Data
  • Random randint() & randrange()
  • Random Choice
  • Random Sample
  • Weighted random choices
  • Random Seed
  • Random Shuffle
  • Get Random Float Numbers
  • Generate Random String
  • Generate Secure random data
  • Secrets to Secure random data
  • Random Data Generation Exercise
  • Random Data Generation Quiz

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com