Making a 0 to n vector in python
Asked Answered
C

4

15

I am a new python user and I was wondering how I could make a 0 to n vector. I would like the user to be able to input an integer for n, and receive an output of [0,1,2,3,4,5...,n].

This is what I have done so far...

from numpy import matrix

n=int(raw_input("n= "))
for i in range(n, 0, -1):
K = matrix(i)
print K

But this is what I get as an output:

[0][1][2][3][4][5]...[n]

Transposing the matrix doesn't help. What am I doing wrong?

Thank you for your help!

Crownwork answered 23/7, 2012 at 3:42 Comment(2)
Use numpy.array instead of numpy.matrixAllin
Your indentation is wrong. You should be getting a SyntaxError.Hexane
P
23

Use the built-in function:

range(n)

(Well, should be n+1 if you want a list to be [0, 1, ... , n])

Petaliferous answered 23/7, 2012 at 3:43 Comment(1)
Just for clarity, this can be used like list(range(n)) to give an array containing each value in the range.Superpatriot
M
13

If you want to use numpy, you can make use of arange:

>>> import numpy as np
>>> np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Mairamaire answered 23/7, 2012 at 4:30 Comment(2)
numpy.linspace can also be very handy for stuff like this.Bacteriolysis
@BiRico worth pointing out linspace always results in a float array, unlike arange which may be integer depending on argumentsRoubaix
A
1
from numpy import array
n = int(raw_input("n= "))
k = array(range(n+1))
print k
Allin answered 23/7, 2012 at 4:8 Comment(0)
I
1

In plain Python (no NumPy dependency):

arr = list(range(10))
print(arr)

(Posting because even if old, browsing for similar problem go to this one. The range() solution is not optimal depending of further tasks (e.g: remove an item arr.remove(val))).

Iridosmine answered 20/9, 2023 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.