55

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']). Commented Jun 6, 2014 at 22:23

4 Answers 4

53

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'])
Sign up to request clarification or add additional context in comments.

Comments

41

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

1 Comment

set.update() will take any iterable and doesn't convert its arguments to sets. The problem is, strings are iterable and yield their characters.
11

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'])

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.