python - Add number to set -


what doing wrong here?

a = set().add(1) print # prints `none` 

i'm trying add number 1 empty set.

it convention in python methods mutate sequences return none.

consider:

>>> a_list = [3, 2, 1] >>> print a_list.sort() none >>> a_list [1, 2, 3]  >>> a_dict = {} >>> print a_dict.__setitem__('a', 1) none >>> a_dict {'a': 1}  >>> a_set = set() >>> print a_set.add(1) none >>> a_set set([1]) 

some may consider convention "a horrible misdesign in python", design , history faq gives reasoning behind design decision (with respect lists):

why doesn’t list.sort() return sorted list?

in situations performance matters, making copy of list sort wasteful. therefore, list.sort() sorts list in place. in order remind of fact, not return sorted list. way, won’t fooled accidentally overwriting list when need sorted copy need keep unsorted version around.

in python 2.4 new built-in function – sorted() – has been added. function creates new list provided iterable, sorts , returns it.

your particular problems feature come misunderstanding of ways create set rather language misdesign. lattyware points out, in python versions 2.7 , later can use set literal a = {1} or a = set([1]) per sven marnach's answer.

parenthetically, ruby's convention of placing exclamation point after methods mutate objects, find python's approach acceptable.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -