If you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers:
import array
array.array('i')
See here
If you need to initialize it,
a = array.array('i',(0 for i in range(0,10)))
Answer from yu_sha on Stack OverflowIf you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers:
import array
array.array('i')
See here
If you need to initialize it,
a = array.array('i',(0 for i in range(0,10)))
two ways:
x = [0] * 10
x = [0 for i in xrange(10)]
Edit: replaced range by xrange to avoid creating another list.
Also: as many others have noted including Pi and Ben James, this creates a list, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array module, as explained in the other answers in this thread.
Hello so I want my input to be an integer of 6 numbers โ123456โ but then print them out as 3 arrays with two integer each f.e. โ12โ, โ34โ, โ56โ. Any idea which way is the easiest?
Let's say I have an array with ints and strs. How do I locate all ints?
Why not just:
pos = [7] * 99
This is the most pythonic, in my opinion.
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!-)
numpy.astype returns a copy of the array. It does not manipulate your array in-place. So you have to assign the value to a variable:
Y = Y.astype(int)
Ok, if we have numpy here and something like that:
Y = np.array([5., 0., 4., 1., 9.])
We can convert each element of array to int like this:
map(int, Y)
To get this result:
[5, 0, 4, 1, 9]