Open In App

Python Program to Print Numbers in an Interval

Improve
Improve
Like Article
Like
Save
Share
Report

Given a range of numbers, find all the numbers between them.

Example:

Input : l = 2, u = 5
Output : 2 3 4 5

Input : l = 10, u = 20 
Output : 10 11 12 13 14 15 16 17 18 19 20

The idea is to use range function in Python

Python3




# Python program to print all the numbers within an interval
l = 10
u = 20
  
for num in range(l, u + 1):
    print(num)


Output:

10
11
12
13
14
15
16
17
18
19
20

Time Complexity: O(N), where N is the difference between l and u.
Auxiliary Space: O(1), As constant extra space is used.

We can also print alternate numbers or numbers with given steps. 

Python3




# Python program to print all EVEN numbers within an interval
l = 10
u = 20
if l%2==0:
    for num in range(l, u + 1, 2):
        print(num)
else:
    for num in range(l+1, u + 1, 2):
        print(num)


Output:

10
12
14
16
18
20

Time Complexity: O(N), where N is the difference between l and u.
Auxiliary Space: O(1), As constant extra space is used.

Another approach is using a list comprehension to generate the numbers in the given interval. List comprehensions are a concise way to create a list by iterating over an iterable and applying a function to each element.

Here’s an example of how you can use a list comprehension to generate the numbers in a given interval:

Python3




# Python program to generate numbers in an interval using a list comprehension
l = 10
u = 20
numbers = [num for num in range(l, u+1)]
print(numbers)
#This code is contributed by Edula Vinay Kumar Reddy


Output

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

This approach has a time complexity of O(n) and a space complexity of O(n), where n is the number of elements in the list.



Last Updated : 13 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads