The study of sets in Python: creation, properties and use for working with unique elements and performing operations on them.

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

What is diversity in Python

In Python, sets are unordered collections of unique (non-repeating) elements. They are one of the main types used in Python, and represent methodological recommendations for specialists with universal knowledge. Many of them are necessary to perform mathematical operations: union, intersection, scatter, and digital scatter.

 

Creating a set in Python

Just a lot

Many people use set() to create this application. It is important to remember that {} creates a simple text, not a multitude.

empty_set = set()
print(type(empty_set))  # class>

Multiple elements

fruits = {"apple", "banana", "cherry"}
print(fruit) # {"apple", "banana", "cherry"}

Reproducing the experience in multiple ways

One of the most common ways to create a set is to transform a list. These are automatic devices that remove all duplications.

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
output(unique numbers) # {1, 2, 3, 4, 5}

Creating a set of strings

text = "hello"
char_set = install(text)
print(character set) # {'h', 'e', 'l', 'o'}

Shared views with many

Adding changes

Method of adding()

Adds confidence in the set. You may even think that a lot of things don't change.

fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruit) # {"apple", "banana", "cherry"}

# Attempt to add an existing
fruit item.add("apple")
print(fruit) # {"apple", "banana", "cherry"} - unchanged

Update method()

Adds uncollectivity to the behavior. Makes iterable decisions.

fruits = {"apple", "banana"}
fruits.update(["cherry", "date"])
print(fruit) # {"apple", "banana", "cherry", "date"}

# You can add items from another set
of fruits.update({"grape", "orange"})
print(fruit) # {"apple", "banana", "cherry", "date", "grape", "orange"}

Seed removal

Deletion method()

Remove from the community. If not found, it causes a key error.

fruits = {"apple", "banana", "cherry"}
fruits.delete("banana")
print(fruit) # {"apple", "cherry"}

# fruits.remove("grapes") # Enter a key error

Deletion method()

The surprising thing is that it exists out of many, or it exists on its own. Ellen does not find, does not evoke a response.

 

fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruit) # {"apple", "cherry"}

fruits.Throw away ("grapes") # Do not grow
a print (fruit) # {"apple", "cherry"}

The pop() method

It surprises and arouses unexpected interest from the multitude. Or at least it causes a key error.

fruits = {"apple", "banana", "cherry"}
delete_fruit = fruits.pop()
print(f"Deleted: {deleted fruit}")
print(fruit)

Cleaning method()

It surprises everyone from the set.

fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits) # set()

Mathematical operations with many

Union of States

Unification creates a new society that unites all people.

a = {1, 2, 3}
b = {3, 4, 5}

# Using the operator |
union_set = a |b
print(union_set) # {1, 2, 3, 4, 5}

# The technique used is union()
union_set = a.union(b)
print(union_set) # {1, 2, 3, 4, 5}

# Union of several sets
with = {6, 7}
union_multiple = a.union(b, c)
outputs(union_multiple) # {1, 2, 3, 4, 5, 6, 7}

Intersection of a set

 

The intersection marks events that occur in many states.

 
a = {1, 2, 3}
b = {3, 4, 5}

# Custom operator &
intersection_set = a &b
print(intersection_set) # {3}

# Intersection method used()
intersection_set = a.intersection(b)
print(intersection_set) # {3}
 

Difference of values

 

The difference reproduces the elements that are in their original form in the set, but not in the second.

 
a = {1, 2, 3}
b = {3, 4, 5}

# Custom operator -
difference_set = a - b
print(difference_set) # {1, 2}

# Using the difference method()
difference_set = a.difference(b)
output(difference_set) # {1, 2}
 

Symmetrical Difference

 

A symbolic ability reproduces elements that are in one place out of many, but not in another.

 
a = {1, 2, 3}
b = {3, 4, 5}

# Using the operator ^
symmetric_difference_set = a ^b
print(symmetric_differentiated set) # {1, 2, 4, 5}

# Use the method symmetric_difference()
symmetric_difference_set = a.symmetric_difference(b)
print(symmetric_difference_set) # {1, 2, 4, 5}
 

Verification of relations between States

 

The issubset() method

 

They claim to be one of the richest people in the world.

 
a = {1, 2, 3}
b = {1, 2, 3, 4, 5}
is_subset = a.issubset(b)
print(is_subset) # True

# Technical result
is_subset = a<= b
print(is_subset) # True
 

The issuerset() method

 

They claim to be one of the most influential people in the world.

 
a = {1, 2, 3, 4, 5}
b = {1, 2, 3}
is_superset = a.issuperset(b)
print(is_superset) # The truth

# Technical result
is_superset = a>=b
print(is_superset) # True
 

The method is disjoint()

 

He claims to have nothing to do with other people.

 
a = {1, 2, 3}
b = {4, 5, 6}
is_disjoint = a.isdisjoint(b)
output(is_disjoint) # True

c = {3, 4, 5}
is_disjoint = a.isdisjoint(c)
print(is_disjoint)  # False
 

User Information

 

Many support iteration, but are not limited to it and are not guaranteed.

 
fruits = {"apple", "banana", "cherry"}
to refer to fruits in fruits:
    Print(fruit)

# Checking the item's ownership
if "apple" is in the fruit:
print ("Apple found in the set")
 

Set generators (Set of concepts)

The generators of many companies can create many with the help of a short notation.

 

 
# A lot of things happened
squares = {x ** 2 for x in the range(10)}
output(squares) # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

# Set of even numbers
even numbers = {x for x in the range(20) if x % 2 == 0}
output(even numbers) # {0, 2, 4, 6, 8, 10, 12, 14, 16, 18}

# Multiple word lengths
words = ["hello", "world", "python", "set"]
word length = {len(word) for a word in words}
print(word length) # {3, 5, 6}

Working for men with friends is just that

 

Life and impressions

 
# Removing characters from the text
of a number = [1, 2, 2, 3, 4, 4, 5]
unique numbers = list(set of(numbers))
output(unique numbers) # [1, 2, 3, 4, 5]

# save duplicates to save in order(
LST):
viewed = installed()
result = []
    for an element in lst:
        if the element is not in seen:
            viewed.add a result (element)
.add(element)
returns the result

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_ordered = deleting duplicationsrelease the order(numbers)
print(uniquely ordered) # [1, 2, 3, 4, 5]
 

Nature and strings

 
# Creating multiple unique character strings
string = "hello world"
unique_chars = set(string)
print(unique characters) # {'d', 'e', 'h', 'l', 'o', 'r', 'w', ' '}

# Removing spaces
unique_chars_no_space = install(string.replace(" ", """))
output(unique_chars_no_space) # {'d', 'e', 'h', 'l', 'o', 'r', 'w'}
 

Family and tuples

The state can support tuples, as they are completely unknown to readers.

 

 
coordinates = {(1, 2), (3, 4), (5, 6)}
output(coordinates)

# Adding new coordinates
coordinates.add((7, 8))
output(coordinates) # {(1, 2), (3, 4), (5, 6), (7, 8)}
 

Society and Words

 
# The key to the word as for many
my_dict = {"a": 1, "b": 2, "c": 3}
set of keys = install(my_dict.keys())
print(set of keys) # {'a', 'b', 'c'}

# Dictionary values as a set
values_set = set(my_dict.values())
output(values_set) # {1, 2, 3}
 

Practical techniques and field techniques

 

Waiting for duplicates during the search

 
definition of find_duplicates(lst):
viewed = installed()
duplicates = installed()
for an element in lst:
        if the item is in the viewed one:
duplicates.add (element)
more:
            viewed.add(element)
to return duplicates

numbers = [1, 2, 2, 3, 4, 4, 5]
duplicates = find duplicates(numbers)
output(duplicates) # {2, 4}
 

Deleting items present in another list

 
list1 = [1, 2, 3, 4, 5]
list2 = [2, 4, 6]
result = list(set(list1) - set(list2))
print(result)  # [1, 3, 5]
 

Search for common items in multiple lists

 
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
list3 = [4, 5, 6, 7, 8]

common_elements = set(list1) & set(list2) & set(list3)
print(common_elements)  # {4, 5}
 

Checking for common elements

 
def have_common_elements(list1, list2):
    return not set(list1).isdisjoint(set(list2))

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [3, 4, 5]

print(have_common_elements(list1, list2))  # False
print(have_common_elements(list1, list3))  # True
 

Frozen Sets (Frozenset)

A Frozenset is an immutable version of a set that can be used as a dictionary key or an element of another set.

 

 
# Creating a frozen array
frozen_set = frozenset([1, 2, 3, 4])
print(frozen_set)  # frozenset({1, 2, 3, 4})

# Use as dictionary
key my_dict = {frozen_set: "value"}
print(my_dict)  # {frozenset({1, 2, 3, 4}): ' value of'}

# Set of frozen sets
set_of_frozensets = {frozenset([1, 2]), frozenset([3, 4])}
print(set_of_frozensets) # {frozenset({1, 2}), frozenset({3, 4})}
 

Performance and optimization

 

Sets provide O(1) element search time, which makes them efficient for:

  •  
  • Checking the item's ownership
  •  
  • Removing duplicates
  •  
  • Mathematical operations on collections
  •  
 
import time

# Comparison of search performance in a list and a set
large_list = list(range(100000))
large_set = set(large_list)

# Search in the list
start = time.time()
99999 in large_list
list_time = time.time() - start

# Search in the set
start = time.time()
99999 in large_set
set_time = time.time() - start

print(f"Search time in the list: {list_time:.6f} seconds")
print(f"Search time in the array: {set_time:.6f} seconds")
 

 

 

Sets in Python are a powerful tool for working with unique data and performing mathematical operations on collections. They provide high performance and code readability when solving tasks related to processing unique elements and multiple operations.

 

table of set methods in Python:

 method
The Description Example The result
add(elem) Adds an element to the set s = {1, 2}; s.add(3) {1, 2, 3}
remove(elem) Deletes an item (error if not present) s = {1, 2, 3}; s.remove(2) {1, 3}
discard(elem) Deletes the element (without error if not) s = {1, 2}; s.discard(3) {1, 2}
pop() Deletes and returns a random element s = {1, 2, 3}; x = s.pop() x = 1 (for example)
clear() Clears the set s = {1, 2, 3}; s.clear() set()
copy() Creates a copy of the set s1 = {1, 2}; s2 = s1.copy() s2 = {1, 2}
update(other) Adds elements from another set s = {1, 2}; s.update({3, 4}) {1, 2, 3, 4}
union(other) Returns the union of sets {1, 2}.union({3, 4}) {1, 2, 3, 4}
intersection(other) Returns the intersection of sets {1, 2, 3}.intersection({2, 3, 4}) {2, 3}
difference(other) Returns the difference of sets {1, 2, 3}.difference({2, 3, 4}) {1}
symmetric_difference(other) Returns the symmetric difference {1, 2, 3}.symmetric_difference({2, 3, 4}) {1, 4}
intersection_update(other) Updates the set by intersection s = {1, 2, 3}; s.intersection_update({2, 3, 4}) {2, 3}
difference_update(other) Updates multiple times s = {1, 2, 3}; s.difference_update({2, 3, 4}) {1}
symmetric_difference_update(other) Updates a set with a symmetric difference s = {1, 2, 3}; s.symmetric_difference_update({2, 3, 4}) {1, 4}
issubset(other) Checks whether it is a subset of {1, 2}.issubset({1, 2, 3}) True
issuperset(other) Checks whether it is a superset {1, 2, 3}.issuperset({1, 2}) True
isdisjoint(other) Checks if there are any common elements {1, 2}.isdisjoint({3, 4}) True
 

Operators for sets:

 method
Operator The Description
` ` union()
& intersection() Intersection
- difference() The difference
^ symmetric_difference() Symmetric difference
` =` update()
&= intersection_update() Intersection update
-= difference_update() Updating by difference
^= symmetric_difference_update() Symmetric difference update
 
 

categories

  • Introduction to Python
  • Python Programming Basics
  • Control Structures
  • Data Structures
  • Functions and Modules
  • Exception Handling
  • Working with Files and Streams
  • File System
  • Object-Oriented Programming (OOP)
  • Regular Expressions
  • Additional Topics
  • General Python Base