Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an array in python [duplicate]

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

like image 804
Sarthak Agarwal Avatar asked Dec 25 '22 07:12

Sarthak Agarwal


1 Answers

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
like image 71
ShadowRanger Avatar answered Jan 05 '23 14:01

ShadowRanger