How can a set be created in Python?

To create a set, you can enclose the elements in curly braces {} and separate the elements with commas.

Here is an example code for creating a collection:

# 创建一个空集合
empty_set = set()
print(empty_set)  # 输出 set()

# 创建一个包含元素的集合
my_set = {1, 2, 3, 4, 5}
print(my_set)  # 输出 {1, 2, 3, 4, 5}

# 创建一个包含重复元素的集合
my_set_with_duplicates = {1, 2, 3, 3, 4, 4, 5}
print(my_set_with_duplicates)  # 输出 {1, 2, 3, 4, 5}

# 使用set()函数创建集合
my_set_using_function = set([1, 2, 3, 4, 5])
print(my_set_using_function)  # 输出 {1, 2, 3, 4, 5}

Please note that sets are unordered and do not allow duplicate elements. If duplicate elements are included when creating a set, the set will automatically remove the duplicates.

bannerAds