1

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!

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Notice that the documentation does this same thing in multiple examples, specifically to show what numbers the example ranges contain. printing a range directly is possible, but what it gives you is not especially useful unless you already understand.
list(range(1,n+1))
True, but it's better to get used to the idea of starting to count from 0 :)
@KarlKnechtel - That is a very simple solution! Thank you!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.