Добавить в корзинуПозвонить
Найти в Дзене

Python sets

In Python, a Set is an unordered collection of Unique elements. This means that a set cannot contain duplicate values. Sets are implemented using a hash table, which allows for very fast membership testing (checking if an element is in the set) and fast insertion and deletion of elements. Key Characteristics of Sets: Unordered: The elements in a set have no specific order. You cannot access elements by index like you can in a list. Unique: Sets only store unique elements. If you try to add a duplicate element, it will be ignored. Mutable: You can add or remove elements from a set after it has been created. Unindexed: You cannot access set elements by their position. Heterogeneous: A set can contain elements of different data types (e. g., integers, strings, floats). However, the elements must be hashable (immutable). Hashable Elements: Elements of a set must be hashable, which means they must be immutable. This includes: Numbers (integers, floats, complex numbers) Strings Tuples Frozen

In Python, a Set is an unordered collection of Unique elements. This means that a set cannot contain duplicate values. Sets are implemented using a hash table, which allows for very fast membership testing (checking if an element is in the set) and fast insertion and deletion of elements.

Key Characteristics of Sets:

Unordered: The elements in a set have no specific order. You cannot access elements by index like you can in a list. Unique: Sets only store unique elements. If you try to add a duplicate element, it will be ignored. Mutable: You can add or remove elements from a set after it has been created. Unindexed: You cannot access set elements by their position. Heterogeneous: A set can contain elements of different data types (e. g., integers, strings, floats). However, the elements must be hashable (immutable). Hashable Elements: Elements of a set must be hashable, which means they must be immutable. This includes:

Numbers (integers, floats, complex numbers) Strings Tuples Frozen sets (discussed later) None

Mutable data types like lists, dictionaries, and other sets Cannot be elements of a set because they are not hashable.

Creating Sets:

There are two main ways to create sets in Python:

Using curly braces {}:

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

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

4.

5. my_set_with_duplicates = {1, 2, 2, 3, 3, 3}

6. print(my_set_with_duplicates) # Output: {1, 2, 3} — duplicates are removed

7.

8. mixed_set = {1, "hello", 3.14, (1, 2)} # Example with different data types

9. print(mixed_set)

Using the Set() constructor:

11. my_set = set([1, 2, 3, 4, 5]) # From a list

12. print(my_set) # Output: {1, 2, 3, 4, 5}

13.

14. my_set = set("hello") # From a string (creates a set of unique characters)

15. print(my_set) # Output: {‘h’, ‘e’, ‘l’, ‘o’}

16.

17. empty_set = set() # Creating an empty set ({} creates an empty dictionary)

18. print(empty_set)

Important: To create an empty set, you Must use set(). Using {} creates an empty dictionary, not an empty set.

Basic Set Operations:

Adding elements: add()

· my_set = {1, 2, 3}

· my_set. add(4)

· print(my_set) # Output: {1, 2, 3, 4}

· my_set. add(2) # adding existing element

· print(my_set) # Output: {1, 2, 3, 4} — no change

Removing elements: remove(), discard()

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

· my_set. remove(2) # Removes 2. Raises KeyError if 2 is not in the set.

· print(my_set) # Output: {1, 3, 4}

·

· my_set. discard(3) # Removes 3. Does *not* raise an error if 3 is not in the set.

· print(my_set) # Output: {1, 4}

·

· # my_set. remove(5) # Raises KeyError: 5 (because 5 is not in the set)

· my_set. discard(5) # Does nothing (no error)

Checking membership: in

· my_set = {1, 2, 3}

· print(2 in my_set) # Output: True

· print(4 in my_set) # Output: False

Length of a set: len()

· my_set = {1, 2, 3}

· print(len(my_set)) # Output: 3

Clearing a set: clear()

· my_set = {1, 2, 3}

· my_set. clear()

· print(my_set) # Output: set()

Set Operations (Mathematical Sets):

Python provides methods for performing common set operations like union, intersection, difference, and symmetric difference.

Union: union() or | (combines elements from both sets)

· set1 = {1, 2, 3}

· set2 = {3, 4, 5}

· union_set = set1.union(set2) # or set1 | set2

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

Intersection: intersection() or & (elements common to both sets)

· set1 = {1, 2, 3}

· set2 = {3, 4, 5}

· intersection_set = set1.intersection(set2) # or set1 & set2

· print(intersection_set) # Output: {3}

Difference: difference() or — (elements in the first set but not in the second)

· set1 = {1, 2, 3}

· set2 = {3, 4, 5}

· difference_set = set1.difference(set2) # or set1 — set2

· print(difference_set) # Output: {1, 2}

Symmetric difference: symmetric_difference() or ^ (elements in either set, but not in both)

· set1 = {1, 2, 3}

· set2 = {3, 4, 5}

· symmetric_difference_set = set1.symmetric_difference(set2) # or set1 ^ set2

· print(symmetric_difference_set) # Output: {1, 2, 4, 5}

Subset: issubset() or <= (checks if one set is a subset of another)

· set1 = {1, 2}

· set2 = {1, 2, 3}

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

· print(set1 <= set2) # Output: True

Superset: issuperset() or >= (checks if one set is a superset of another)

· set1 = {1, 2, 3}

· set2 = {1, 2}

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

· print(set1 >= set2) # Output: True

Disjoint: isdisjoint() (checks if two sets have no elements in common)

· set1 = {1, 2, 3}

· set2 = {4, 5, 6}

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

Frozen Sets:

A frozenset is an immutable version of a set. This means that once a frozenset is created, you cannot add or remove elements from it. Frozen sets are hashable, so they can be used as elements of other sets or as keys in dictionaries.

My_set = frozenset([1, 2, 3])

# my_set. add(4) # Raises AttributeError: ‘frozenset’ object has no attribute ‘add’

Another_set = {my_set, 4, 5} # Using a frozenset as an element of another set

Print(another_set) # Output: {frozenset({1, 2, 3}), 4, 5}

When to Use Sets:

Removing duplicates: Sets are very efficient at removing duplicate elements from a list or other iterable. Membership testing: Checking if an element is present in a set is very fast. Mathematical set operations: Performing operations like union, intersection, difference, and symmetric difference. Storing unique elements: When you need to ensure that a collection contains only unique values.

Example: Removing Duplicates from a List:

My_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

Unique_list = list(set(my_list)) # Convert the set back to a list

Print(unique_list) # Output: [1, 2, 3, 4]

In conclusion, sets are a powerful and versatile data structure in Python for working with unordered collections of unique elements. They offer efficient membership testing and support for common set operations. Choose sets when you need to ensure uniqueness, perform set-based calculations, or prioritize fast membership checks.