49

I am new to Python. When I added a string with add() function, it worked well. But when I tried to add multiple strings, it treated them as character items.

>>> set1 = {'a', 'bc'}
>>> set1.add('de')
>>> set1
set(['a', 'de', 'bc'])
>>> set1.update('fg', 'hi')
>>> set1
set(['a', 'g', 'f', 'i', 'h', 'de', 'bc'])
>>>

The results I wanted are set(['a', 'de', 'bc', 'fg', 'hi'])

Does this mean the update() function does not work for adding strings?

The version of Python used is: Python 2.7.1

1
  • 2
    Try set1.update(['fg', 'hi']). Jun 6, 2014 at 22:23

4 Answers 4

46

You gave update() multiple iterables (strings are iterable) so it iterated over each of those, adding the items (characters) of each. Give it one iterable (such as a list) containing the strings you wish to add.

set1.update(['fg', 'hi'])
40

update treats its arguments as sets. Thus supplied string 'fg' is implicitly converted to a set of 'f' and 'g'.

1
  • set.update() will take any iterable and doesn't convert its arguments to sets. The problem is, strings are iterable and yield their characters.
    – kindall
    Apr 27 at 12:49
10

Here's something fun using pipe equals ( |= )...

>>> set1 = {'a', 'bc'}
>>> set1.add('de')
>>> set1
set(['a', 'de', 'bc'])
>>> set1 |= set(['fg', 'hi'])
>>> set1
set(['a', 'hi', 'de', 'fg', 'bc'])
6

Try using set1.update( ['fg', 'hi'] ) or set1.update( {'fg', 'hi'} )

Each item in the passed in list or set of strings will be added to the set

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.