How to declare an array in python
Solution 1
As noted in the comments, initializing a list
(not an array, that's not the type in Python, though there is an array
module for more specialized use) to a bunch of zeroes is just:
a = [0] * 10000
If you want an equivalent to memset
for this purpose, say, you want to zero the first 1000 elements of an existing list
, you'd use slice assignment:
a[:1000] = [0] * 1000
Solution 2
You can initialize a list of a given size in several ways.
Python has list comprehensions, which create lists from other lists inline. So, if you make a list with 10000 elements (range(10000)
) you can easily make from this a list with 10000 zeroes:
[0 for _ in range(10000)]
This is pretty close to your original solution.
Probably a more efficient approach is to multiply a list with a single zero by 10000:
[0]*10000
Both will yield a list with 10000 zeroes.
Solution 3
There is a call to "memset" from CPython:
from cpython cimport array
import array
cdef array.array a = array.array('i', [1, 2, 3])
# access underlying pointer:
print a.data.as_ints[0]
from libc.string cimport memset
memset(a.data.as_voidptr, 0, len(a) * sizeof(int))
Comments
-
Sarthak Agarwal almost 2 years
I want to assign values to different indices and not in a sequential manner(by using append), like we would do in a hash table. How to initialize the array of a given size? What I do:
a=[] for x in range(0,10000): a.append(0)
Is there a better way? Also, is there any function like memset() in c++?