Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 457
JackWM Avatar asked Jun 06 '14 22:06

JackWM


People also ask

How do you add strings to a set?

The easiest way to add a single item to a Python set is by using the Python set method, . add() . The method acts on a set and takes a single parameter, the item to add. The item being added is expected to be an immutable object, such as a string or a number.

How do you add values to a set in Python?

The set add() method adds a given element to a set if the element is not present in the set. Syntax: set. add(elem) The add() method doesn't add an element to the set if it's already present in it otherwise it will get added to the set.


1 Answers

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

like image 90
user58697 Avatar answered Sep 29 '22 11:09

user58697