How to use the set function in Python?

The set() function is used to create a set, which is a collection of unique and unordered elements.

Here is how to use it:

  1. Create an empty set.
my_set = set()
  1. Create a collection that contains elements.
my_set = set([1, 2, 3, 4, 5])
  1. Add elements to the collection.
my_set.add(6)
  1. Remove elements from the collection.
my_set.remove(1)
  1. Set operations:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)  # 求并集
intersection_set = set1.intersection(set2)  # 求交集
difference_set = set1.difference(set2)  # 求差集
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds