Search code examples
pythonarrayslistinitialization

Simple way to create an incrementing Python array


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!


Solution

  • 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.