0

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?

4 Answers4

4

You could use recursion to print first n natural numbers

def printNos(n):

    if n > 0:

        printNos(n-1)
        print n

printNos(100)
Nihal Rp
  • 436
  • 4
  • 14
3

Looping will be required in some form or another to generate a list of numbers, whether you do it yourself, use library functions, or use recursive methods.

If you're not opposed to looping in principle (but just don't want to implement it yourself), there are many practical and esoteric ways to do it (a number have been mentioned here already).

A similar question was posted here: How to fill a list. Although it has interesting solutions, they're all still looping, or using range type functions.

Community
  • 1
  • 1
roelofs
  • 1,992
  • 17
  • 24
3

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]
Francisco C
  • 8,871
  • 4
  • 31
  • 41
2

Well, yes, you can do this without using range, loop or recursion:

>>> num = 10
>>> from subprocess import call
>>> call(["seq", str(num)])

You can even have a list (or a generator, of course):

>>> num = 10
>>> from subprocess import check_output
>>> ls = check_output(["seq", str(num)])
>>> [int(num) for num in ls[:-1].split('\n')]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42]

But...what's the purpose?

nalzok
  • 11,870
  • 17
  • 57
  • 105
  • Can you provide a link to some documentation on this? It seems a novel approach. – roelofs Oct 19 '16 at 05:52
  • @roelofs I'm just [calling an external command](http://stackoverflow.com/a/89243/5399734). POSIX command [`seq`](http://man.cx/seq) can print a sequence of numbers, which seems to be what OP wants. – nalzok Oct 19 '16 at 05:55
  • Thanks! We're having a discussion on whether OP meant **any** looping, or just looping it himself. Cool solution :) – roelofs Oct 19 '16 at 05:56