What am I doing wrong here?
a = set().add(1)
print a # Prints `None`
I'm trying to add the number 1
to the empty set.
What am I doing wrong here?
a = set().add(1)
print a # Prints `None`
I'm trying to add the number 1
to the empty set.
The
add()
method adds an element to the set, but it does not return the set again -- it returnsNone
.or better
would work.
Because
add()
is modifing your set in place returningNone
:It is a convention in Python that methods that mutate sequences return
None
.Consider:
Some may consider this convention "a horrible misdesign in Python", but the Design and History FAQ gives the reasoning behind this design decision (with respect to lists):
Your particular problems with this feature come from a misunderstanding of good ways to create a set rather than a language misdesign. As Lattyware points out, in Python versions 2.7 and later you can use a set literal
a = {1}
or doa = set([1])
as per Sven Marnach's answer.Parenthetically, I like Ruby's convention of placing an exclamation point after methods that mutate objects, but I find Python's approach acceptable.
You are assigning the value returned by
set().add(1)
to a. This value isNone
, asadd()
does not return any value, it instead acts in-place on the list.What you wanted to do was this:
Of course, this example is trivial, but Python does support set literals, so if you really wanted to do this, it's better to do:
The curly brackets denote a set (although be warned,
{}
denotes an empty dict, not an empty set due to the fact that curly brackets are used for both dicts and sets (dicts are separated by the use of the colon to separate keys and values.)Alternatively to a = set() | {1} consider "in-place" operator:
Another way to do it that is relatively simple would be:
this creates a union between your set a and a set with 1 as the element
print(a) yields {1} then because a would now have all elements of both a and {1}