Add number to set

2019-01-18 01:20发布

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.

标签: python set
8条回答
SAY GOODBYE
2楼-- · 2019-01-18 01:52

The add method updates the set, but returns None.

a = set()
a.add(1)
print a
查看更多
时光不老,我们不散
3楼-- · 2019-01-18 01:56

You should do this:

a = set()
a.add(1)
print a

Notice that you're assigning to a the result of adding 1, and the add operation, as defined in Python, returns None - and that's what is getting assigned to a in your code.

Alternatively, you can do this for initializing a set:

a = set([1, 2, 3])
查看更多
登录 后发表回答