how to use range in python

Published on Aug. 22, 2023, 12:15 p.m.

The range() function in Python generates an immutable sequence of integers. It can be used in a for loop to perform a repetitive task a certain number of times, or to create a list of numbers with a specific pattern. Here are a few examples:

  1. To generate a sequence of integers from 0 to n-1:
for i in range(n):
    print(i)
  1. To generate a sequence of integers from start to end-1:
for i in range(start, end):
    print(i)
  1. To generate a sequence of integers from start to end-1 with a specific step size:
for i in range(start, end, step):
    print(i)

Here’s an example of how to create a list of even numbers between 4 and 12 using the range() function:

even_numbers = list(range(4, 13, 2))
print(even_numbers)

This will output [4, 6, 8, 10, 12], which is the list of even numbers between 4 and 12 with a step size of 2.

Tags: