-5

I have array:

somearray = np.array([])

I want to set array on position 10 to have True value

somearray[10]= True

I want to add on spot 10, and I wish that spots 0-9 would be filled with nothing. How can I do this, without index being out of bounds?

TioneB
  • 468
  • 3
  • 12

2 Answers2

1

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.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

If your nothing means null or nan, you can try the below code (reference: https://stackoverflow.com/a/20606278/9584980)

import numpy as np
size = 20
somearray = np.full([size,],np.nan)
somearray[10] = True # but this would make the element to 1. as nans are considered as float. you can change np.nan to False if you literally want a True here

EDITED:

If you need to use numpy methods only at the end, you can just store all the required indices and later create a numpy array of the desired size and populate the Trues accordingly.

One more way is to first declare a numpy array of the size as the index that you need (10 in your example). And later resize it if the next index you need to populate is bigger than the array.

index = 10
somearray = np.full([index+1,], False)
somearray[index] = True

#if the next index you need to make true is 20 then
index = 20
somearray.resize([index+1,], refcheck=False)
somearray[index] = True
KBN
  • 153
  • 1
  • 8