How to add multiple strings to a set in Python?

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


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


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

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