Reputation: 518
I am wanting to initialize an array (in Python) that goes from 1 to some number n
. I am wondering how I would do that in the simplest way...
In this answer, they share a way to initialize an array with all the same value, but I want to initialize mine to be more like this: [1,2,3,4,5,6,7,8,9,10]
if n = 10
I know I could do something like:
n = int(input("Enter a number: "))
arr = 0 * n
for (i in range(len(arr))):
arr[i] = i+1
But I want it simpler... I'm sort of new to Python, so I don't know a whole lot. Would someone be able to show me how (and explain it or give a reference) to initialize an "incrementing array"?
Thank you!
Upvotes: 1
Views: 4370
Reputation: 182
Update Based on Karl's answer, you should have something like this :
arr = list(range(1, n+1))
print(arr)
======================================================= I'm not really sure about your question. but let me try
n = int(input("Enter a number: "))
arr = []
for i in range (1,n+1):
arr.append(i)
print(arr)
use append
to add any item to the tail of the array.
Upvotes: 1
Reputation: 61498
But I want it simpler
Make sure you understand how range
works and what it actually does. Since it is already a sequence, and since it already contains the exact values you want, all you need to do in order to get a list is to convert the type, by creating a list from the range.
It looks like:
list(range(n))
Yep, that's it.
Upvotes: 4