Minimize memory consumption when working with python list assignment

I have two high-sized lists of integers. The size of each list exceeds 200,000. My task is this: given the two lists

a = [None, 0, None, None, 0, None, None, None, 0, None, None, None, None, None, 0,...]
b = [7 1 4 8 2 1 1 1 1 6 1 6 1 4 4 1 1 6 6 7 4 4 7 5...]

the number Noneis equal to the length b

My question is how to replace everything Noneon aevery element in b, using minimal memory .

My method

j = 0
for i in range(len(a)):
    if a[i] == None:
        while j < len(b):   
            a[i] = b[j]
            break
        j = j+1   

Since my program uses a lot of memory, I really need to save memory. Could you give me some ideas on how to preserve memory in this situation?

+4
source share
1 answer

b, , a None, next(b_iter) .

b_iter = iter(b)
a = [next(b_iter) if i is None else i for i in a]

>>> a = [None, 0, None, None, 0, None, None, None, 0, None, None, None, None, None, 0]
>>> b = [7, 1, 4, 8, 2, 1, 1, 1, 1, 6, 1]
>>> b_iter = iter(b)
>>> [next(b_iter) if i is None else i for i in a]
[7, 0, 1, 4, 0, 8, 2, 1, 0, 1, 1, 1, 6, 1, 0]
+3

All Articles