Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: How to use a list comprehension to replace Nones in one list with values from another list?

a = [0,   -4, 4,    6, 2, 5, 8]
b = [5, None, 3, None, 3, 2, 0]
c = [5,   -4, 3,    6, 3, 2, 0]

I want to take a and b as inputs and get c, ideally using a list comprehension. Obviously I could iterate through this with a loop, but I’m wondering if there is a more elegant/pythonic solution.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this should work:

c = [value if value is not None else a[index] for index, value in enumerate(b)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading