What is the usage of the range function in Python?

The range() function is a commonly used built-in function in Python for generating a sequence of integers. Its typical form is range(start, stop, step), where start represents the initial value of the sequence (default is 0), stop is the end value of the sequence (not included), and step is the interval between adjacent values in the sequence (default is 1).

The range() function can be used to generate an iterable object containing a series of integers, which can be used in a for loop or converted to a list. Here are some examples of using the range() function:

  1. Use range to generate integers from 0 to 9.
  2. Print numbers from 0 to 9.
  3. Generate integers from 1 to 10 using range.
  4. for each number from 1 to 10, print the number
  5. Generate even numbers from 1 to 10 using range:
  6. Print the numbers from 2 to 10 in increments of 2.
  7. Convert range to a list.
  8. my_list = list(range(5))
    print(my_list) # Output is [0, 1, 2, 3, 4]

It should be noted that the range() function returns a list in Python 2.x, while it returns an iterable object in Python 3.x. If you need to directly get a list, you can use the list() function to convert the result of range() into a list.

bannerAds