Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to set in the form of list comprehension in Python

I have a list of sets. I want to add an element to each of these sets, and I want to do this with list comprehension. This is what I have tried:

In [1]: sets1 = [set()]

In [2]: sets2 = [{1,2}, {1,2,3}]

In [3]: [e.add(0) for e in sets1]
Out[3]: [None]

In [4]: [e.add(0) for e in sets2]
Out[4]: [None, None]

My desired output is:

[{0}]
[{1,2,0}, {1,2,3,0}]

Why does the above code return None instead of an addition of elements to the list, and how I can make this work?

like image 206
CentAu Avatar asked Nov 04 '25 03:11

CentAu


1 Answers

I would suggest:

[e | {0} for e in sets1]

or:

[e.union({0}) for e in sets1]
like image 147
Dan D. Avatar answered Nov 05 '25 17:11

Dan D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!