Python Basic Operations-collection

Source: Internet
Author: User

In Python set is a collection type of the base data type, which has both a mutable set (set ()) and an immutable set (Frozenset). Creating Set Sets, collection set additions , collection deletions , intersections , sets , and difference sets is a very useful approach.

List_1 = Set ([1,3,5,7,5,8,10])

List_2 = Set ([2,3,4,5,6,7,8])

List_3 = Set ([1,3,5])

One: basic operation

Adding an Add

List_1.add (123)
Print (list_1)
{1, 3, 5, 7, 8, 10, 123}

Add multiple Update

List_1.update ([10,20,30,50])
Print (list_1)
{1, 3, 5, 7, 8, 10, 50, 20, 30}

Delete Remove if not in the list will be an error

List_1.remove (1)
Print (list_1)
{3, 5, 7, 8, 10}

List_1.remove (20)
Print (list_1)


Traceback (most recent):
File "d:/pycharm/day1/collection test. Py", line +, in <module>
List_1.remove (20)
Keyerror:20

Delete Discard If nothing in the list does not error

List_1.discard (20)
Print (list_1)
{1, 3, 5, 7, 8, 10}

Delete Pop randomly deletes a member

List_1.pop ()
Print (list_1)
{3, 5, 7, 8, 10}

Two: Relationship Testing

Intersection

Print (List_1.intersection (list_2))

{8, 3, 5, 7}

and set

Print (List_1.union (list_2))

{1, 2, 3, 4, 5, 6, 7, 8, 10}

Subtraction

Print (List_1.difference (list_2))

{1, 10}

Subset

Print (List_3.issubset (list_1))

True

Parent Set

Print (List_1.issuperset (list_3))

True

Symmetric difference Sets

Print (List_1.symmetric_difference (list_2))

{1, 2, 4, 6, 10}

Python Basic Operations-collection

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.