Class

Python Interview Questions for range() function


The range() function in Python is commonly used in loops and other places where an iterable is needed. Below are some sample Python interview questions and answers that focus on the Python range() function:

Question 1: What is the range() function in Python?

Answer: The range() function in Python is a built-in function that generates a sequence of numbers over time. It’s commonly used in for loops and other places where you need to iterate over a range of numbers.

Question 2: How do you create a range from 0 to 9 using range()?

Answer: You can create a range from 0 to 9 using range(10).

Python
for i in range(10):
    print(i)

This will print numbers from 0 to 9.

Question 3: Can range() function generate a sequence of floating-point numbers?

Answer: No, the range() function only works with integers. It cannot generate a sequence of floating-point numbers.

Question 4: How do you use range() to iterate over a list by index?

Answer: You can use range() with len() to iterate over a list by index:

Python
my_list = [10, 20, 30, 40, 50]
for i in range(len(my_list)):
    print(my_list[i])

Question 5: How would you generate a sequence of numbers in descending order using range()?

Answer: You can specify the start, stop, and step parameters in range() to generate numbers in descending order. For example, range(10, 0, -1) will generate numbers from 10 to 1 in descending order.

Python
for i in range(10, 0, -1):
    print(i)

This will print numbers from 10 to 1.

Question 6: Is range() an iterator or an iterable?

Answer: range() is an iterable, not an iterator. It does, however, return an iterator that produces the numbers in the sequence when iterated over.

Question 7: What is the time complexity of the range() function?

Answer: The range() function has a time complexity of O(1) for accessing an individual element and generating the sequence is also O(1) because it does not actually create a list; it just iterates over the numbers in the specified range.