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: Append same element to multiple lists

I have a snippet of code that repeats itself and is annoying/looks ugly. I have 4 lists and I need to add "nan" to all multiple times at different points of code.
It looks like this:

a, b, c, d = []

...

a.append(np.nan)
b.append(np.nan)
c.append(np.nan)
d.append(np.nan)

I would like a more elegant solution (single-line) to append nan to all those lists.

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

Any ideas?

>Solution :

In could be written in one line, but it looks terrible.

[cur_list.append(np.nan) for cur_list in [a,b,c,d]]

I would recommend at least 2 lines, to have some readability.

for cur_list in [a,b,c,d]:
    cur_list.append(np.nan)
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