0

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.

Any ideas?

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Wow that was fast, thx! Readability is precisely what I am going for, so using solution #2 above. Got stuck because of ugly code, now trying to untangle to understand a bug in the logic. I haven´t been able to run it but sure this does the trick... I will a comment later in case I run into trouble, thanks!
Please do not use the first code. It is a misuse of a list comprehension for side-effects. I do not understand the urge to squeeze some code to a single line :( If you really want to have the code on a single line, use the for loop (single-command body can be on the same line) ----------------------------------------------------- for cur_list in [a, b, c, d]: cur_list.append(np.nan)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.