JackWM
JackWM

Reputation: 10565

How to add multiple strings to a set in Python?

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

Upvotes: 54

Views: 47298

Answers (4)

Swoop
Swoop

Reputation: 544

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

Upvotes: 11

kindall
kindall

Reputation: 184395

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

Upvotes: 50

wallacer
wallacer

Reputation: 13213

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

Upvotes: 6

user58697
user58697

Reputation: 7923

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

Upvotes: 41

Related Questions