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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.