Perhaps the closest thing in Python to this Javascript array behavior is a dictionary. It’s a hashed mapping.
defaultdict is a dictionary that implements a default value.
In [1]: from collections import defaultdict
In [2]: arr = defaultdict(bool)
Insert a couple of True elements:
In [3]: arr[10] = True
In [4]: arr
Out[4]: defaultdict(bool, {10: True})
In [5]: arr[20] = True
In [6]: arr
Out[6]: defaultdict(bool, {10: True, 20: True})
Fetching some other element returns the default (False in this case), and adds it to the dictionary:
In [7]: arr[3]
Out[7]: False
In [8]: arr
Out[8]: defaultdict(bool, {3: False, 10: True, 20: True})
defaultdict(list) is a handy way of collecting values in lists within the dictionary. defaultdict(int) implements a counter.
numpy arrays have a fixed size, and specified dtype:
In [21]: x = np.zeros(8, bool)
In [22]: x[5]=True
In [23]: x
Out[23]: array([False, False, False, False, False, True, False, False])
You can make a new array by concatenating with something else (forget the np.append function).
Python lists can be initialed to a empty size, alist= [], and can grow with append or extend. But you can’t grow the list by indexing.
0
solved Python arrays in numpy