I have two lists:
a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]
I want to merge them, either to create a new list or just update a, by filling in the Nones with the values from b, so
a = [7,8,1,2,4,3,6,5,9]
What's the most efficient way of doing this?
For extension, I'll be wanting to do this with every permutation of b. Does this allow shortcutting the technique at all?
This is one approach. Using a list comprehension and converting b
to a iterator object.
Demo:
a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]
b = iter(b)
print( [next(b) if i is None else i for i in a] )
Output:
[7, 8, 1, 2, 4, 3, 6, 5, 9]
With list.pop()
method on reversed 2nd b
list:
a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]
tmp = b[::-1]
result = [tmp.pop() if i is None else i for i in a]
print(result) # [7, 8, 1, 2, 4, 3, 6, 5, 9]
for reversed_index in range(len(a) - 1, -1, -1):
if a[reversed_index] is None:
a[reversed_index] = b.pop()
It should be efficient as it modifies a
in place and right popping a list is also efficient. As far as I think, it is an O(len(a))
solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With