I'm taking this online Python course and trying to solve the following problem called Coding Exercise: It's Natural:
Write a function naturalNumbers which takes a positive integer n as input, and returns a list [1, 2, ...] consisting of the first n natural numbers.
Do I even need a for loop to create a list? Here's my code (which doesn't work obviously). Keep in mind, they have not taught list comprehension. I found this concept on stackoverflow.
def naturalNumbers(n):
list = [n+1 for i in n]
return list
Should I take another approach where I create multiple lists of 1,2,3...n and concatenate them all together like [1] + [2] + [3]....
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))
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments