4

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++?

Sarthak Agarwal
  • 128
  • 1
  • 2
  • 16

3 Answers3

6

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
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
3

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.

Luke Taylor
  • 8,631
  • 8
  • 54
  • 92
1

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))
armatita
  • 12,825
  • 8
  • 48
  • 49
  • There is no indication that the OP actually wants to initialize a C array here. And definitely no indication of a desire to use Cython (which is _not_ the same thing as CPython; CPython refers to the reference interpreter which happens to be implemented in C). – ShadowRanger Mar 20 '16 at 13:11
  • In the post you can read "Also, is there any function like memset() in c++?" What the OP chooses to use to solve it's problem is pretty much his decision. Down-voting an answer just because it does not fit your idea of solution is a bit narrow from my point of view. But I'll defer to more informed opinion. If I see my post does not provide useful information for OP I'll delete it. – armatita Mar 20 '16 at 13:17
  • Even if the OP doesn't find the answer useful, somebody else reading this question may. If it's a legitimate answer and provides a new perspective on the problem, it is free to keep around and there is no need to delete it. See http://meta.stackoverflow.com/questions/256350/should-i-delete-my-question-if-it-got-negative-votes%3E – MANA624 Mar 21 '16 at 06:28