CentAu
CentAu

Reputation: 11160

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?

Upvotes: 3

Views: 4746

Answers (4)

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

Let's first regenerate your problem.

>>> test_set = set()
>>> test_set
set()
>>> print(test_set.add(0))
None
>>> test_set
{0}
>>> 

As you can see, test_set.add(0) returns None. But this is an in place operation, so the item did get added., which is evident from the above snippet.


How to solve the problem:

You can union after making the element a set rather than using the add method.

>>> [i.union({0}) for i in sets2]
[{0, 1, 2}, {0, 1, 2, 3}]

If you have a list/set of element to add to the exiting list of sets, you can do the following:

elements_to_add = [3,4,5]
>>> [i.union(set(elements_to_add)) for i in sets2]
[{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}]

However, this is not an in-place operation. sets2 would be exactly same before and after running the above list comprehension.

Upvotes: 1

MSeifert
MSeifert

Reputation: 152647

I wouldn't use a list comprehension in this case, a plain for loop would be simpler:

for subset in sets1:
    subset.add(0)

print(sets1)

should give you the desired output.

I already pointed it out in the comments why your approach seemingly did not work:

set.add works in place and does not return anything (thus your Nones). If you want your desired output then run the list-comprehension but don't save its result. Check your set1 and set2 after the list-comprehension to get the desired output.

So you could just check sets1 and sets2 after the list comprehension. It should return: [{0}] and [{1,2,0}, {1,2,3,0}] (order may vary because sets are unordered).

Upvotes: 2

Hou Lu
Hou Lu

Reputation: 3222

Actually your sets1 and sets2 variables have become the results that you want, because the add statement operates the sets1 but not generate a new list.
You can print(sets1) and print(sets2) to testify.

Upvotes: 1

Dan D.
Dan D.

Reputation: 74655

I would suggest:

[e | {0} for e in sets1]

or:

[e.union({0}) for e in sets1]

Upvotes: 7

Related Questions