How to write a function that takes a positive integer N and returns a list of the first N natural numbers
There are two problems with your attempt.
First, you've used n+1
instead of i+1
, so you're going to return something like [5, 5, 5, 5]
instead of [1, 2, 3, 4]
.
Second, you can't for
-loop over a number like n
, you need to loop over some kind of sequence, like range(n)
.
So:
def naturalNumbers(n):
return [i+1 for i in range(n)]
But if you already have the range
function, you don't need this at all; you can just return range(1, n+1)
, as arshaji showed.
So, how would you build this yourself? You don't have a sequence to loop over, so instead of for
, you have to build it yourself with while
:
def naturalNumbers(n):
results = []
i = 1
while i <= n:
results.append(i)
i += 1
return results
Of course in real-life code, you should always use for
with a range
, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range
function first, just to use it for naturalNumbers
. (It's already pretty close.)
There is one more option, if you want to get clever.
If you have a list, you can slice it. For example, the first 5 elements of my_list
are my_list[:5]
. So, if you had an infinitely-long list starting with 1
, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count
or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice
. So:
from itertools import count, islice
def naturalNumbers(n):
return list(islice(count(1), n))
Do I even need a for loop to create a list?
No, you can (and in general circumstances should) use the built-in function range()
:
>>> range(1,5)
[1, 2, 3, 4]
i.e.
def naturalNumbers(n):
return range(1, n + 1)
Python 3's range()
is slightly different in that it returns a range
object and not a list, so if you're using 3.x wrap it all in list()
: list(range(1, n + 1))
.
Here are a few ways to create a list with N of continuous natural numbers starting from 1.
1 range:
def numbers(n):
return range(1, n+1);
2 List Comprehensions:
def numbers(n):
return [i for i in range(1, n+1)]
You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!