What does ‘set’ mean in Python?

In Python, `set` is an unordered and mutable collection data type that does not allow duplicate elements. It can be used to store a unique set of elements.

A `set` object can be created using curly braces `{}` or the `set()` function. For example:

# 使用花括号创建一个set

my_set = {1, 2, 3, 4, 5}

print(my_set)  # 输出: {1, 2, 3, 4, 5}

# 使用set()函数创建一个set

another_set = set([5, 6, 7, 8, 9])

print(another_set)  # 输出: {5, 6, 7, 8, 9}

The main features of set include:

The elements in the set are unordered, so they cannot be accessed by index.

The elements in the set are unique, any duplicate elements will be automatically removed.

3. A set is mutable and allows for adding, removing, and modifying elements.

The elements in a set must be hashable (immutable), therefore they cannot contain mutable types of elements such as lists, dictionaries, etc.

5. You can manipulate sets using a variety of built-in methods such as adding elements with `add()`, removing elements with `remove()`, finding the union with `union()`, and finding the intersection with `intersection()`.

Here are some common operations examples for the `set`.

my_set.add(6)  # 添加元素

my_set.remove(3)  # 移除元素

print(len(my_set))  # 输出: 5,集合中的元素个数

print(2 in my_set)  # 输出: True,判断元素是否在集合中

union_set = my_set.union(another_set)  # 求并集

intersection_set = my_set.intersection(another_set)  # 求交集

print(union_set)  # 输出: {1, 2, 4, 5, 6, 7, 8, 9}

print(intersection_set)  # 输出: {5}

In conclusion, `set` is a very useful data type, particularly suitable for handling unordered, unique collections of elements.

bannerAds