Python's update set

Source: Internet
Author: User

Python's update set

Because set stores a set of unordered elements that are not duplicated, the update set mainly does two things:

One is to add the new element to the set, and the other is to remove the existing element from the set.

when adding an element, use the Add () method of Set :

>>> s = Set ([1, 2, 3]) >>> S.add (4) >>> print Sset ([1, 2, 3, 4])

If the added element already exists in set, add () will not error, but will not be added:

>>> s = Set ([1, 2, 3]) >>> S.add (3) >>> print sset ([1, 2, 3])

when removing elements from a set, use the Remove () method of Set :

>>> s = Set ([1, 2, 3, 4]) >>> S.remove (4) >>> print Sset ([1, 2, 3])

If the deleted element does not exist in the set, remove () will error:

>>> s = Set ([1, 2, 3]) >>> S.remove (4) Traceback (most recent):  File ' <stdin> ', line 1 , in <module>keyerror:4

So with Add () can be added directly, and remove () before you need to judge.

Task

For the following set, given a list, for each element in the list, if it is in set, it is deleted, if it is not in the set, it is added.

s = set ([' Adam ', ' Lisa ', ' Paul ']) L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
? What's going on?

Determines whether the element is in set, using the in operator.

Reference code:

s = set ([' Adam ', ' Lisa ', ' Paul ']) L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']for name in L: the    if name in S:        s.remove (name) 
     else:        s.add (name) print S

Python's update set

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.