rpin
rpin

Reputation: 35

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.

Any ideas?

Upvotes: 0

Views: 382

Answers (1)

Finn
Finn

Reputation: 2343

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)

Upvotes: 3

Related Questions