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
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.
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.
update
treats its arguments as sets. Thus supplied string 'fg'
is implicitly converted to a set of 'f' and 'g'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With