How to add multiple strings to a set in Python?

Question:

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

Asked By: JackWM

||

Answers:

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

Answered By: wallacer

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'])
Answered By: kindall

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

Answered By: user58697

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'])
Answered By: Swoop
orignal_set = {'evening',1} 

#adding element using Set add() method
orignal_set.add('Good')
 
#adding element that already exists in set
orignal_set.add(1)
 
print('set after adding element :',orignal_set)
Answered By: JRG Prasanna
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.