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?
I would suggest:
[e | {0} for e in sets1]
or:
[e.union({0}) for e in sets1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With