4

How I can define array of integer numbers in Python code

Say if this code is ok. or no

pos = [int]

len = 99

for i in range (0,99):
    pos[i]=7
2
  • 1
    Perhaps you should explain your goal some. It's not too too common to fill up a list like this. Commented May 25, 2010 at 4:19
  • You do not need to declare types in Python. [int] defines a list of one element, which is the int type (as a first-class object itself). Commented May 25, 2010 at 6:15

6 Answers 6

11

Why not just:

pos = [7] * 99

This is the most pythonic, in my opinion.

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

Comments

5
import array

pos = array.array('l', 7 * [99])

The array module of Python's standard library is the only way to make an array that comes with Python (the third-party module numpy offers other ways, but needs do be downloaded and installed separately) -- what your Q is doing, as well as every answer so far, is building a list, not an array.

In particular, there is no constraint that the pos list built in your Q and the several As contains just integers -- while, with the snippet I give, you do get that constraint (32-bit signed integers in this case, to be precise), which rigidly limits you but also saves a bunch of memory (an array of integers should take about one fifth the amount of memory that a list filled with integers will take, unless there's a lot of perennial duplication in the lists' items).

BTW, if you say array when you mean list (just in case list is what you meant), you're sure to cause a lot of confusion -- saying what you mean, and meaning what you say, helps a lot in clear communication, unsurprisingly!-)

1 Comment

0 <= Probability("OP means array.array, not list" | code_in_the_question) < epsilon
4

you do not declare the type of variables in python, so no pos=[int] all you have to do:

pos=[]
for i in range(99):
    pos.append(7)

Comments

2

You can simply do

pos = [7] * 99
print pos #will print the whole array [7, 7, .... 7]

Comments

1

If you just want to declare the array, all you have to do in python is:

pos = []

If you want to fill the array with 99 7's:

pos = [7] * 99

If you want to fill the array based on a pattern:

pos = [i for i in range(99)]

Comments

0

One way is:

pos = [7 for _ in xrange(0,99)]

in Python 2 or:

pos = [7 for _ in range(0,99)]

in Python 3. These are list comprehensions, and are easy to extend for more complex work.

Also:

pos = [int]

doesn't make much sense. You're creating a list with the only element being the type int.

1 Comment

xrange(0, 99)==xrange(99): the first element is zero, by default!

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.