A detailed explanation of how to use Python’s set function

The set function is a built-in function in Python that is used to convert iterable objects such as lists, tuples, strings, etc. into set objects. Sets are a data type in Python that consist of unordered collections of unique elements.

Here is the syntax for the set function:

set(iterable)

Among them, iterable is an object that can be iterated over, such as lists, tuples, strings, and so on.

The purpose of the set function is to remove duplicate elements from an iterable object and then return a new collection object. The elements in the collection object are unordered and unique.

Here are common usages and examples of the set function:

  1. Convert a list to a set.
my_list = [1, 2, 3, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set)  # 输出:{1, 2, 3, 4, 5}
  1. Convert a tuple to a set.
my_tuple = (1, 2, 3, 3, 4, 4, 5)
my_set = set(my_tuple)
print(my_set)  # 输出:{1, 2, 3, 4, 5}
  1. Convert the string to a set.
my_string = "hello"
my_set = set(my_string)
print(my_set)  # 输出:{'h', 'e', 'l', 'o'}
  1. Convert multiple elements into a set.
my_set = set(1, 2, 3, 3, 4, 4, 5)
print(my_set)  # 输出:{1, 2, 3, 4, 5}

It’s important to note that the elements in the set object returned by the set function are unordered and unique. If an ordered set object is needed, the sorted function can be used to sort the set object.

In addition, the collection object also supports some common collection operations such as union, intersection, difference, etc. These operations can be performed using methods or operators of the collection object. For example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# 并集
union_set = set1.union(set2)
print(union_set)  # 输出:{1, 2, 3, 4, 5}

# 交集
intersection_set = set1.intersection(set2)
print(intersection_set)  # 输出:{3}

# 差集
difference_set = set1.difference(set2)
print(difference_set)  # 输出:{1, 2}

The above is a detailed explanation of how to use the set function. With the set function, it is easy to convert iterable objects into set objects and perform set operations.

Leave a Reply 0

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