Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate for range in python

Tags:

python

If I have to generate natural numbers, I can use 'range' as follows:

list(range(5))

[0, 1, 2, 3, 4]

Is there any way to achieve this without using range function or looping?

like image 366
Flying Dutchmann Avatar asked Jan 17 '26 15:01

Flying Dutchmann


2 Answers

You could use recursion to print first n natural numbers

def printNos(n):

    if n > 0:

        printNos(n-1)
        print n

printNos(100)
like image 66
Nihal Rp Avatar answered Jan 20 '26 07:01

Nihal Rp


Based on Nihal's solution, but returns a list instead:

def recursive_range(n):
    if n == 0:
        return []
    return recursive_range(n-1) + [n-1]
like image 42
Francisco Avatar answered Jan 20 '26 05:01

Francisco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!