Python set (with examples) (2023)

A set is a collection of unique data. That is, elements of a set cannot be duplicated. For example,

Suppose we want to store information aboutstudent ID cards. Sincestudent ID cardscannot be duplicated, we can use a set.

Python set (with examples) (1)

Create a sentence in Python

In Python, we create sets by placing all elements in curly braces{}, separated by commas.

A set can have any number of elements and they can be of different types (integer, float, tuple, string, etc.). But a set cannot have mutable elements likeListen, sentences ordictionariesas its elements.

Let's look at an example

# Make a series of integers typestudent_id = {112, 114, 116, 118, 115}print('Student ID:', student_id)# Make a series of strings typevowel_letters = {'a', 'e', 'i', 'o', 'u'}print('Vowel Letters:', vowel_letters)# create a mixed datatype setmixed_set = {'Hello', 101, -2, 'Bye'}print('Mixed datatype set: ', mixed sentence)

Exit

Student ID: {112, 114, 115, 116, 118}Vocal Letters: {'u', 'a', 'e', ​​'i', 'o'}Mixed Data Type Set: {'hello', ' Goodbye', 101, -2}

In the example above, we created different types of sets by placing all the elements inside the curly brackets{}.

Note:If you run this code, you may get output in a different order. This is because the set is in no particular order.

Create an empty set in Python

Creating an empty set is a bit tricky. Empty braces{}will make a blankdictionaryin Python.

To create a set with no elements, we use theSentence()Function with no argument. For example,

# create an empty setempty_set = set()# create an empty dictionaryempty_dictionary = { }# check the data type of empty_setprint('data type of empty_set:', type(empty_set))# check the data type of dictionary_setprint('data type of empty_dictionary' , type (empty_dictionary))

Exit

(Video) SETS INTRODUCTION - PYTHON PROGRAMMING

Data type of empty_set: <class 'set'>Data type of empty_dictionary <class 'dict'>

Here,

  • empty set- an empty set created withSentence()
  • empty_dictionary- an empty dictionary created with{}

Finally we used itTyp()Function to know which classempty setAndempty_dictionarybelong.

Duplicate items in one set

Let's see what happens when we try to include duplicate elements in a sentence.

numbers = {2, 4, 6, 6, 2, 8}print(numbers) # {8, 2, 4, 6}

Here we can see that the set does not contain any duplicate elements, since a set cannot contain any duplicates.

Adding and updating set items in Python

Quantities are variable. However, since they are unordered, the indexing has no meaning.

We cannot access or modify an element of a set using indexing or slicing. Set data type does not support it.

Adding elements to a set in Python

In Python we use theadd to()Method for adding an element to a set. For example,

Zahlen = {21, 34, 54, 12}print('Initial Set:',Zahlen)# using add() methodnumbers.add(32)print('Updated Set:', Numbers)

Exit

First set: {34, 12, 21, 54} Updated set: {32, 34, 12, 21, 54}

In the example above, we created a set namedPay. notice the line

numbers.add(32)

Here,add to()adds32to our sentence.

(Video) Python Tutorial: Sets - Set Methods and Operations to Solve Common Problems

Update Python set

TheTo update()method is used to update the set with elements of other collection types (lists, tuples, sets, etc.). For example,

Companies = {'Lacoste', 'Ralph Lauren'}tech_companies = ['apple', 'google', 'apple']companies.update(tech_companies)print(companies)# Output: {'google', 'apple', ' Lacoste', 'Ralph Lauren'}

Here are all the unique elements oftech_companyare addedcompaniesSentence.

Remove an element from a set

We use thatdiscard()method to remove the specified element from a set. For example,

languages ​​​​= {'Swift', 'Java', 'Python'}print('Initial Set:',languages)# remove 'Java' from a SetremovedValue = languages.discard('Java')print('Set after remove () :', Languages)

Exit

Initial Set: {'Python', 'Swift', 'Java'}Set after remove(): {'Python', 'Swift'}

Here we used thatdiscard()remove method'Java'of theLanguagesSentence.

Built-in functions with set

Built-in functions likeat(),any(),enumerate(),len(),max(),Minimum(),sorted (),Total()etc. are commonly used with sentences to perform various tasks.

functionDescription
at()ReturnsTRUEif all elements of the set are true (or if the set is empty).
any()ReturnsTRUEif any member of the set is true. If the lot is empty, will be returnedINCORRECT.
enumerate()Returns an enumeration object. It contains the index and value for all members of the set as a pair.
len()Returns the length (the number of elements) in the set.
max()Returns the largest element in the set.
Minimum()Returns the smallest element in the set.
sorted ()Returns a new sorted list of elements in the set (does not sort the set itself).
Total()Returns the sum of all elements in the set.

Iterate over a crowd in Python

fruits = {"apple", "peach", "mango"}# For loop to access each fruit for fruits in fruits: print(fruit)

Exit

MangoPfirsichApfel

Find the number of set elements

We can use thoselen()Method to get the number of elements present in a set. For example,

even_numbers = {2,4,6,8}print('Set:',even_numbers)# Find number of elements print('Total Elements:', len(even_numbers))

Exit

Theorem: {8, 2, 4, 6} Total elements: 4

Here we used thatlen()Method to get the number of elements present in a set.

(Video) What are Sets in Python? Python Tutorial for Absolute Beginners | Mosh

The Python Set Operation

Python Set provides several built-in methods for performing mathematical set operations such as union, intersection, subtraction, and symmetric difference.

Union of two sets

The union of two setsAAndBcontain all elements of setAAndB.

Python set (with examples) (2)

We use that|operator or theUnion()-Method to perform set union operation. For example,

# first setA = {1, 3, 5}# second setB = {0, 2, 4}# union operation with |print('Union using |:', A | B)# union operation with union()print perform ('Union using union():', A.union(B))

Exit

Union with |: {0, 1, 2, 3, 4, 5} Union with union(): {0, 1, 2, 3, 4, 5}

note:A|BAndUnion()is equivalent toA⋃Bstop operation.

set intersection

The intersection of two setsAAndBcontain the common elements between setAAndB.

Python set (with examples) (3)

In Python we use the&operator or theOverlap()-Method to perform set cutting operation. For example,

# first setA = {1, 3, 5}# second setB = {1, 2, 3}# intersection operation with &print('intersection with &:', A & B)# intersection operation with intersection()print( 'intersection with intersection ():', A.Intersection(B))

Exit

Intersection with &: {1, 3}Intersection with intersection(): {1, 3}

note:A&BAndOverlap()is equivalent toA⋂Bstop operation.

difference between two sentences

The difference between two sentencesAAndBContain elements of setAthat are not present on the setB.

Python set (with examples) (4)

We use that-operator or theDifference()Method to run the difference between two sentences. For example,

(Video) Python Tutorial for Beginners 4: Lists, Tuples, and Sets

# first setA = {2, 3, 5}# second setB = {1, 2, 6}# difference operation with &print('difference with &:', A - B)# difference operation with difference()print( 'difference with difference ():', A.difference(B))

Exit

Difference with &: {3, 5} Difference with Difference(): {3, 5}

note:A-BAndA. Difference (B)is equivalent toA-Bstop operation.

Set symmetrical difference

The symmetric difference between two setsAAndBcontains all elements ofAAndBwithout the common elements.

Python set (with examples) (5)

In Python we use the^operator or theSymmetric_difference()Method for performing a symmetrical difference between two sentences. For example,

# first setA = {2, 3, 5}# second setB = {1, 2, 6}# difference operation with &print('using ^:', A ^ B)# with symmetric_difference()print('using symmetric_difference( ): ', A.symmetric_difference(B))

Exit

mit ^: {1, 3, 5, 6} mit symmetric_difference(): {1, 3, 5, 6}

Check if two sentences are equal

We can use those==Operator to check if two sets are equal or not. For example,

# first setA = {1, 3, 5}# second setB = {3, 5, 1}# perform difference operation with &if A == B: print('set A and set B are equal')else: print(' set A and sentence B are not the same')

Exit

Set A and Set B are the same

In the example aboveAAndBhave the same elements, i.e. the condition

if A == B

evaluatesTRUE. Hence the statementprint('Set A and Set B are the same')within theIfis running.

Other Python Set Methods

There are many set methods, some of which we have used above. Here is a list of all the methods available with the Set objects:

MethodDescription
add to()Adds an item to the set
clear()Removes all items from the set
Copy()Returns a copy of the set
Difference()Returns the difference of two or more sets as a new set
difference_update()Removes all elements of another set from this set
discard()Removes an item from the set if it is a member. (Do nothing if item is not in set)
Overlap()Returns the intersection of two sets as a new set
intersection_update()Updates the set with the intersection of itself and another
is disjoint ()ReturnsTRUEif two sets have a zero intersection
issubset()ReturnsTRUEif another sentence contains this sentence
superset()ReturnsTRUEif this sentence contains another sentence
Pop()Removes and returns any set item. Elevatedkey errorwhen the crowd is empty
removed()Removes an item from the set. If the element is not a member, a is thrownkey error
Symmetric_difference()Returns the symmetric difference of two sets as a new set
symmetric_difference_update()Updates a set with the symmetric difference of itself and another
Union()Returns the union of sets into a new set
To update()Updates the crowd with the union of self and others
(Video) Sets in Python || Python Tutorial || Learn Python Programming

Videos

1. Python sets 🍴
(Bro Code)
2. Python Sets And Dictionaries | Python Sets | Python Dictionaries | Python Tutorial | Simplilearn
(Simplilearn)
3. How To Use Sets in Python (Python Tutorial #13)
(CS Dojo)
4. Sets In Python | Python Sets Tutorial | Python Tutorial for Beginners | Edureka
(edureka!)
5. What are Sets in Python - Explained with Examples | Python Tutorial
(WsCube Tech)
6. Python Tutorial - 24. Sets and Frozen Sets
(codebasics)
Top Articles
Latest Posts
Article information

Author: Allyn Kozey

Last Updated: 03/13/2023

Views: 5811

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.