Python set Methods

Phyllis 34 Published: 06/17/2024

Python set Methods

Here's a detailed explanation of various set methods in Python:

1. set() function: This is used to create a new set object. The argument passed should be iterable (can be a list, tuple, dictionary, etc.) and this method will automatically remove any duplicates.

Example:

set1 = set([1, 2, 3, 4, 5])

print(set1) # Output: {1, 2, 3, 4, 5}

2. update() method: This is used to add elements from another set or any iterable to the current set.

Example:

set1 = set([1, 2, 3])

set2 = set([3, 4, 5])

set1.update(set2)

print(set1) # Output: {1, 2, 3, 4, 5}

3. intersect() method: This is used to find the common elements between two sets.

Example:

set1 = set([1, 2, 3, 4, 5])

set2 = set([3, 4, 5, 6, 7])

print(set1.intersection(set2)) # Output: {3, 4, 5}

4. union() method: This is used to combine two sets into one.

Example:

set1 = set([1, 2, 3])

set2 = set([3, 4, 5])

print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}

5. difference() method: This is used to find the elements in one set that are not present in another.

Example:

set1 = set([1, 2, 3])

set2 = set([3, 4, 5])

print(set1.difference(set2)) # Output: {1, 2}

6. symmetric_difference() method: This is used to find the elements that are not common between two sets.

Example:

set1 = set([1, 2, 3])

set2 = set([3, 4, 5])

print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}

7. isdisjoint() method: This is used to check if two sets are disjoint (have no elements in common).

Example:

set1 = set([1, 2, 3])

set2 = set([4, 5, 6])

print(set1.isdisjoint(set2)) # Output: True

8. issubset() method: This is used to check if one set is a subset of another.

Example:

set1 = set([1, 2, 3])

set2 = set([1, 2, 3, 4, 5])

print(set1.issubset(set2)) # Output: True

9. issuperset() method: This is used to check if one set is a superset of another.

Example:

set1 = set([1, 2, 3])

set2 = set([1, 2, 3])

print(set1.issuperset(set2)) # Output: True

10. copy() method: This is used to create a copy of the current set.

Example:

set1 = set([1, 2, 3])

set2 = set1.copy()

print(set1) # Output: {1, 2, 3}

print(set2) # Output: {1, 2, 3} (newly created)

How to create lists in Python?

I'm happy to help! However, I must follow the rules you provided. Hence, I'll respond in Simplified Chinese.

my_list = []

my_tuple = ('a', 'b', 'c')

my_list = list(my_tuple)

my_list = ['a', 'b']

my_tuple = ('c', 'd')

my_list.extend(my_tuple)

my_list = ['a', 'b']

my_list.append('c')

my_list = ['a', 'b']

my_list.insert(1, 'c')

my_list = ['c', 'a', 'b']

my_list.sort()

my_list.reverse()

my_list = [i**2 for i in range(5)]