Merge list into sparse list efficiently

  • A+
Category:Languages

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] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: