Python range function

The range() method in Python returns the sequence of a number inside a given range. Python has a built-in function called range(). When a user needs to repeat an action a certain number of times, this is the method to utilize. range() in Python 3.x is simply a renamed version of the Python method xrange (2.x). The range() method is used to create a numeric sequence.

Because Python’s range() method is frequently used in loops, understanding it is essential when working with Python code. Iterating sequence types in Python range() List, string, etc. with for and while loops is the most popular application of the range () method in Python.

Basics of Python range()

Range(), in its most basic form, allows the user to generate a series of numbers inside a particular range. Depending on how many arguments the user passes to the function, the user can choose where the sequence of numbers begins and ends and how significant the difference between one number and the next will be. range() accepts three arguments in total.

The range syntax is as follows:

range(start, stop, step)
  • start: the first integer in the sequence of integers to be returned.
  • stop: the integer before which the integer sequence is returned. stop – 1 is the end of the integer range.
  • step: The integer value determines the increase between each integer in the sequence.

range() returns a value

Depending on the definitions used, range () returns an immutable sequence object of numbers.

Example: Demonstration of Python range()

# Program for showing the range () basics

# how to print a number using range(
for i in range(5):
	print(i, end=" ")
print()

# illustrating how range  is useful in iteration
num_list = [11, 12, 13, 14, 15, 16, 17,18, 19, 20]
for i in range(len(num_list)):
	print(l[i], end=" ")
print()

# natural number summation
sum_val = 0
for i in range(15, 21):
	sum_val = sum_val + i
print("Sum of natural numbers is :", sum_val)

You can use range () in three different ways:

  • There is only one parameter to range (stop).
  • There are two arguments to range (start, stop).
  • There are three arguments to range (start, stop, step).

range(stop)

When you call range () with just one argument, you’ll get a list of numbers that starts at 0 and goes all the way up to, but not including, the number you provide as the stop.

As an example:

# program for printing whole numbers using the range ()

# first 5 whole numbers
for i in range(5):
	print(i, end=" ")
print()

# printing the first 9 whole numbers
for i in range(9):
	print(i, end=" ")

Here, x is the loop’s implementation range, while n denotes the value in each iteration. It’s worth noting that the output always comes before the stop value; it’s never a part of the range iteration, as it is with a list.size().

range (start, stop)

When you call range () with two arguments, you can choose where the series of numbers ends and where it begins, so you don’t have to start at 0. The range() function is responsible for generating a series of numbers from X to Y. (X, Y). For instance, -arguments

# program for printing natural numbers using a range

#print numbers from 50 to 55
for i in range(50, 56):
	print(i, end=" ")
print()


# print the natural number from 5 t0 9
for i in range(5, 10):
	print(i, end=" ")
print()

range (start, stop, step)

When a user calls range () with three arguments, they can specify where the series of numbers will begin and end and how much the difference between each number will be. Though the user does not specify a step, range () will act as if the step is 1.

# program for printing all numbers divisible by 5 and 3


# using range for printing numbers divisible by 5
for i in range(25, 50, 5):
	print(i, end=" ")
print()

# using range in printing numbers divisible by 3
for i in range(21, 30, 3):
	print(i, end=" ")
print()

Instead of incrementing by one, the loop increments by three on each iteration because the step value is three in the last example above. One of the most crucial things to remember is that the step value should never be 0; otherwise, a ValueError exception will be thrown.

Iteration across several forms of lists

Range() is also used to iterate through the list types using the len function and access the values via the index, in addition to loops. Take a peek at:

list_of_computers = ['HP', 'Chrome Book', 'DELL', 'Apple']

for i in range(len(list_of_computers )):
  print(list_of_computers [I])

Using range to make a list, a set, or a tuple

Instead of being limited to writing loops, range () is helpful in various circumstances. To reduce boilerplate code, we use the range function to build List, Set, and Tuple instead of loops. Take a peek at:

print(list(range(5, 15, 2)))

print(tuple(range(5, 15, 2)))

print(set(range(5, 15, 2)))

We may pass negative values in step to construct ascending order lists to make things a little more interesting. Take a peek at:

print(list(range(15, 5, -2)))

print(tuple(range(15, 5, -2)))

for loop with a range ()

A for loop in Python repeats a block of code or a statement for a set number of times. We may iterate over a sequence of numbers generated by the range() function using the for loop. Let’s look at how to print odd numbers between 1 and 10 using a for loop and the range () method. In this example, we can see how the iterator variable i gets its value when we use range () with a for loop.

for i in range(5, 18, 2):
  print("Current value of i is:", i)

To comprehend what for i in range () means in Python, we must first understand the range () function’s operation. The generator is used by the range () function to generate numbers. It does not generate all of the numbers at the same time.

range(), as you may know, returns the range object. Regardless of the size of the range it represents, a range object utilizes the same (small) amount of memory. Only the start, stop, and step values are stored, and individual items and subranges are calculated as needed.

That is, it only generates the next value when it is requested by the for loop iteration. It generates the next value and assigns it to the iterator variable i with each loop iteration. The variable i does not receive the values 1, 3, 5, 7, and 9 simultaneously, as in the output. The value of i in the first iteration of the loop is the start number of a range. The step value then increments the value of i in each subsequent iteration of the for loop. The formula i = i + step is used to calculate the value of i.

As the loop progresses to the following iteration, range () produces numbers one by one. Range() is faster and more efficient because it saves a lot of memory.

Example: Using a positive step to increment the range

If a user wants to increment, the user must have a positive number of steps. Consider the following scenario:

# program for incrementing with the range ()


# increments by 4
for i in range(24, 36, 4):
	print(i, end=" ")
print()

# incremented by 2
for i in range(2, 8, 2):
	print(i, end=" ")
print()

# increments by 3
for i in range(21, 33, 3):
	print(i, end=" ")

Example: Backwards range () in Python

We can use positive or negative numbers for any of the parameters in the range. This feature allows for the creation of reverse loops. If a user wants to decrease, the steps must be negative. We can accomplish this by specifying a higher index as the start value and a negative step value as the step value. Consider the following scenario:

# program for decrementing with the range ()



# incremented by -4
for i in range(36, 24, -4):
	print(i, end=" ")
print()

# increments by -2
for i in range(8, 2, -2):
	print(i, end=" ")
print()

# increments by -3
for i in range(33, 21, -3):
	print(i, end=" ")

Example: Range() float in Python

The range () method in Python does not support float numbers. i.e., no floating-point or non-integer numbers are used in any argument. Users are limited to using only integer numbers.

As an example,

# program for illustrating float number in range()

# using a float number
for i in range(4.8):
	print(i)

# using a float number
for i in range(9.3):
	print(i)

However, we can construct a new Python method similar to the one below as a workaround. The step argument can now be specified as a float value.

Import decimal

def float_range(start, stop, step):
  while start < stop:
    yield float(start)
    start += decimal.Decimal(step)

print(list(float_range(0, 4, '0.2')))

Example: Concatenation of two range () methods

The chain() method of the itertools module combines the results of two range() procedures. The chain() method prints all the values in iterable targets, one by one, as specified in its arguments.

# program for concatenating two range functions' results

from itertools import chain

# chain method in play
print("result concatenation")
res_val = chain(range(8), range(12, 21, 2))

for i in res_val:
	print(i, end=" ")

Example: Using the index value to access range ()

The range() function returns a sequence of numbers as an object that its index value can retrieve. Its object supports both positive and negative indexing.

# program for illustrating the range function

element = range(8)[0]
print("The starting element is:", element)

element = range(8)[-1]
print("\nLast element:", element)

element = range(8)[4]
print("\nThe fourth element:", element)

The range () method in Python has a few things to keep in mind:

  • The range() method is only used with integers or whole numbers.
  • Integers are used for all parameters.
  • Users cannot pass a string, float number, or any other type in a range’s start, stop and step arguments ().
  • Each of the three reasons might be construed in either a good or negative light.
  • The value of the step cannot be zero.
  • Python throws a ValueError exception if a step is zero.
  • range() is a Python type.
  • Users can use the index to access items in a range(), just like they can with a list.

Conclusion

The range() function returns a number series that starts at 0 by default and increments by 1 (by default) before stopping at a specified value. Most programmers use the range to build loops since it returns a succession of numbers. The latter is vital when you don’t have access to a list or tuple and only need to create a loop with a single value.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *