SlideShare a Scribd company logo
1 of 20
PYTHON SETS
Python Sets
• Sets are used to store multiple items in a single
variable.
• Set is one of 4 built-in data types in Python used to
store collections of data, the other 3 are List, Tuple,
and Dictionary, all with different qualities and usage.
• A set is a collection which
is unordered, unchangeable*, and unindexed.
• * Note: Set items are unchangeable, but you can
remove items and add new items.
• Sets are written with curly brackets.
Cont..
• Example
• Create a Set:
• thisset = {"apple", "banana", "cherry"}
print(thisset)
• Output: {'apple', 'banana', 'cherry’}
• # Note: the set list is unordered, meaning: the items will appear in a
random order.
• Note: Sets are unordered, so you cannot be sure in
which order the items will appear.
• Set Items
• Set items are unordered, unchangeable, and do not
allow duplicate values.
Cont..
• Unordered
• Unordered means that the items in a set do not have a
defined order.
• Set items can appear in a different order every time you use
them and cannot be referred to by index or key.
• Unchangeable
• Set items are unchangeable, meaning that we cannot
change the items after the set has been created.
• Once a set is created, you cannot change its items, but you
can remove items and add new items.
• Duplicates Not Allowed
• Sets cannot have two items with the same value.
Cont..
• Example
• Duplicate values will be ignored:
• thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
• Output: {'banana', 'cherry', 'apple’}
• Get the Length of a Set
• To determine how many items a set has, use the len() function.
• A set can contain different data types:
• Example
• A set with strings, integers and boolean values:
• set1 = {"abc", 34, True, 40, "male"}
• type()
• From Python's perspective, sets are defined as objects with the
data type 'set':
• <class 'set'>
Cont..
• Access Items
• You cannot access items in a set by referring to an index or a key.
• But you can loop through the set items using a for loop or ask if a
specified value is present in a set, by using the in keyword.
• Example
• Loop through the set, and print the values:
• thisset = {"apple", "banana", "cherry"}
• for x in thisset:
• print(x)
• Output: banana
• apple
• cherry
Cont..
• Example
• Check if "banana" is present in the set:
• thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
• Output: True
• Change Items
• Once a set is created, you cannot change its items, but you can
add new items.
• Add Items
• To add one item to a set, use the add() method.
• Example
• Add an item to a set, using the add() method:
• thisset = {"apple", "banana", "cherry"}
• thisset.add("orange")
• print(thisset)
• Output:{'orange', 'banana', 'cherry', 'apple'}
Cont..
• Add Sets
• To add items from another set into the current set, use the update()
method.
• Example
• Add elements from tropical into thisset:
• thisset = {"apple", "banana", "cherry"}
• tropical = {"pineapple", "mango", "papaya"}
• thisset.update(tropical)
• print(thisset)
• Output: {'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}
Cont..
• Add Any Iterable
• The object in the update() method does not have to be a set, it can be
any iterable object (tuples, lists, dictionaries etc.).
• Example
• Add elements of a list to at set:
• thisset = {"apple", "banana", "cherry"}
• mylist = ["kiwi", "orange"]
• thisset.update(mylist)
• print(thisset)
• Output: {'banana', 'cherry', 'apple', 'orange', 'kiwi'}
Cont..
• Remove Item
• To remove an item in a set, use the remove(), or the discard()
method.
• Example
• Remove "banana" by using the remove() method:
• thisset = {"apple", "banana", "cherry"}
• thisset.remove("banana")
• print(thisset)
• Output: {'cherry', 'apple’}
• Note: If the item to remove does not exist, remove() will raise an
error.
Cont..
• Example:
• thisset = {"apple", "cherry"}
• thisset.remove("banana")
• print(thisset)
• Output: File "./prog.py", line 3, in <module>
• KeyError: 'banana’
• Example
• Remove "banana" by using the discard() method:
• thisset = {"apple", "banana", "cherry"}
• thisset.discard("banana")
• print(thisset)
• Output: {'apple', 'cherry’}
• Note: If the item to remove does not exist, discard() will NOT raise an error.
Cont..
• You can also use the pop() method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not know
what item that gets removed.
• The return value of the pop() method is the removed item.
• thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
• Output: banana
• {'cherry', 'apple’}
• Example
• The clear() method empties the set:
• thisset = {"apple", "banana", "cherry"}
• thisset.clear()
• print(thisset)
• Output: set()
Cont..
• Example
• The del keyword will delete the set completely:
• thisset = {"apple", "banana", "cherry"}
• del thisset
• print(thisset)
• Output: File "demo_set_del.py", line 5, in <module>
• print(thisset) #this will raise an error because the set no
longer exists
• NameError: name 'thisset' is not defined
• Python - Loop Sets
• Same as in list and tuples
Cont..
• Join Two Sets
• There are several ways to join two or more sets in Python.
• You can use the union() method that returns a new set containing all
items from both sets, or the update() method that inserts all the
items from one set into another:
• Example
• The union() method returns a new set with all items from both sets:
• set1 = {"a", "b" , "c"}
• set2 = {1, 2, 3}
• set3 = set1.union(set2)
• print(set3)
• Output: {'c', 'b', 1, 'a', 2, 3}
Cont..
• Example
• The update() method inserts the items in set2 into set1:
• set1 = {"a", "b" , "c"}
• set2 = {1, 2, 3}
• set1.update(set2)
• print(set1)
• Output: {'a', 2, 'c', 1, 3, 'b’}
• Note: Both union() and update() will exclude any duplicate items.
• Keep ONLY the Duplicates
• The intersection_update() method will keep only the items that are present in both sets.
• Example
• Keep the items that exist in both set x, and set y:
• x = {"apple", "banana", "cherry"}
• y = {"google", "microsoft", "apple"}
• x.intersection_update(y)
• print(x)
• Output: {'apple'}
Cont..
• The intersection() method will return a new set, that only contains
the items that are present in both sets.
• Example
• Return a set that contains the items that exist in both set x, and set y:
• x = {"apple", "banana", "cherry"}
• y = {"google", "microsoft", "apple"}
• z = x.intersection(y)
• print(z)
• Output: {'apple'}
Cont..
• Keep All, But NOT the Duplicates
• The symmetric_difference_update() method will keep only the
elements that are NOT present in both sets.
• Example
• Keep the items that are not present in both sets:
• x = {"apple", "banana", "cherry"}
• y = {"google", "microsoft", "apple"}
• x.symmetric_difference_update(y)
• print(x)
• Output:
• {'google', 'banana', 'microsoft', 'cherry'}
Cont..
• The symmetric_difference() method will return a new set, that
contains only the elements that are NOT present in both sets.
• Example
• Return a set that contains all items from both sets, except items that
are present in both:
• x = {"apple", "banana", "cherry"}
• y = {"google", "microsoft", "apple"}
• z = x.symmetric_difference(y)
• print(z)
• Output: {'google', 'banana', 'microsoft', 'cherry'}
Cont..
Cont..

More Related Content

What's hot

Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in pythonhydpy
 
Tiempo de ejecución de un algoritmo
Tiempo de ejecución de un algoritmoTiempo de ejecución de un algoritmo
Tiempo de ejecución de un algoritmoFernando Solis
 
Introduction to Set Theory
Introduction to Set TheoryIntroduction to Set Theory
Introduction to Set TheoryUsama ahmad
 
Sets PowerPoint Presentation
Sets PowerPoint PresentationSets PowerPoint Presentation
Sets PowerPoint PresentationAshna Rajput
 
Program in ‘C’ language to implement linear search using pointers
Program in ‘C’ language to implement linear search using pointersProgram in ‘C’ language to implement linear search using pointers
Program in ‘C’ language to implement linear search using pointersDr. Loganathan R
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonLifna C.S
 
Sequential & binary, linear search
Sequential & binary, linear searchSequential & binary, linear search
Sequential & binary, linear searchmontazur420
 
Sets (Mathematics class XI)
Sets (Mathematics class XI)Sets (Mathematics class XI)
Sets (Mathematics class XI)VihaanBhambhani
 

What's hot (20)

Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
8.unit-1-fds-2022-23.pptx
8.unit-1-fds-2022-23.pptx8.unit-1-fds-2022-23.pptx
8.unit-1-fds-2022-23.pptx
 
Sets
SetsSets
Sets
 
Set concepts
Set conceptsSet concepts
Set concepts
 
Tiempo de ejecución de un algoritmo
Tiempo de ejecución de un algoritmoTiempo de ejecución de un algoritmo
Tiempo de ejecución de un algoritmo
 
Dictionary
DictionaryDictionary
Dictionary
 
Introduction to Set Theory
Introduction to Set TheoryIntroduction to Set Theory
Introduction to Set Theory
 
Arrays Basics
Arrays BasicsArrays Basics
Arrays Basics
 
Complement of a set
Complement of a setComplement of a set
Complement of a set
 
Descriptive Statistics in R.pptx
Descriptive Statistics in R.pptxDescriptive Statistics in R.pptx
Descriptive Statistics in R.pptx
 
Sets PowerPoint Presentation
Sets PowerPoint PresentationSets PowerPoint Presentation
Sets PowerPoint Presentation
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
ARRAY
ARRAYARRAY
ARRAY
 
Array in-c
Array in-cArray in-c
Array in-c
 
Program in ‘C’ language to implement linear search using pointers
Program in ‘C’ language to implement linear search using pointersProgram in ‘C’ language to implement linear search using pointers
Program in ‘C’ language to implement linear search using pointers
 
Functions in mathematics
Functions in mathematicsFunctions in mathematics
Functions in mathematics
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Subsets
SubsetsSubsets
Subsets
 
Sequential & binary, linear search
Sequential & binary, linear searchSequential & binary, linear search
Sequential & binary, linear search
 
Sets (Mathematics class XI)
Sets (Mathematics class XI)Sets (Mathematics class XI)
Sets (Mathematics class XI)
 

Similar to Python_Sets(1).pptx

Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...KavineshKumarS
 
list and control statement.pptx
list and control statement.pptxlist and control statement.pptx
list and control statement.pptxssuser8f0410
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology InitiativeBasil Bibi
 
Decision control units by Python.pptx includes loop, If else, list, tuple and...
Decision control units by Python.pptx includes loop, If else, list, tuple and...Decision control units by Python.pptx includes loop, If else, list, tuple and...
Decision control units by Python.pptx includes loop, If else, list, tuple and...supriyasarkar38
 
Week 10.pptx
Week 10.pptxWeek 10.pptx
Week 10.pptxCruiseCH
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
Set data structure
Set data structure Set data structure
Set data structure Tech_MX
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptxNawalKishore38
 
Data Type In Python.pptx
Data Type In Python.pptxData Type In Python.pptx
Data Type In Python.pptxhothyfa
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdfCEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdfvtunali
 

Similar to Python_Sets(1).pptx (20)

Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
 
Python Lists.pptx
Python Lists.pptxPython Lists.pptx
Python Lists.pptx
 
Python Tuples.pptx
Python Tuples.pptxPython Tuples.pptx
Python Tuples.pptx
 
list and control statement.pptx
list and control statement.pptxlist and control statement.pptx
list and control statement.pptx
 
Lists
ListsLists
Lists
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Decision control units by Python.pptx includes loop, If else, list, tuple and...
Decision control units by Python.pptx includes loop, If else, list, tuple and...Decision control units by Python.pptx includes loop, If else, list, tuple and...
Decision control units by Python.pptx includes loop, If else, list, tuple and...
 
LIST_tuple.pptx
LIST_tuple.pptxLIST_tuple.pptx
LIST_tuple.pptx
 
Week 10.pptx
Week 10.pptxWeek 10.pptx
Week 10.pptx
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Set data structure
Set data structure Set data structure
Set data structure
 
List in Python
List in PythonList in Python
List in Python
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
 
Data Type In Python.pptx
Data Type In Python.pptxData Type In Python.pptx
Data Type In Python.pptx
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdfCEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
 
Sets
SetsSets
Sets
 

Recently uploaded

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

Python_Sets(1).pptx

  • 2. Python Sets • Sets are used to store multiple items in a single variable. • Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. • A set is a collection which is unordered, unchangeable*, and unindexed. • * Note: Set items are unchangeable, but you can remove items and add new items. • Sets are written with curly brackets.
  • 3. Cont.. • Example • Create a Set: • thisset = {"apple", "banana", "cherry"} print(thisset) • Output: {'apple', 'banana', 'cherry’} • # Note: the set list is unordered, meaning: the items will appear in a random order. • Note: Sets are unordered, so you cannot be sure in which order the items will appear. • Set Items • Set items are unordered, unchangeable, and do not allow duplicate values.
  • 4. Cont.. • Unordered • Unordered means that the items in a set do not have a defined order. • Set items can appear in a different order every time you use them and cannot be referred to by index or key. • Unchangeable • Set items are unchangeable, meaning that we cannot change the items after the set has been created. • Once a set is created, you cannot change its items, but you can remove items and add new items. • Duplicates Not Allowed • Sets cannot have two items with the same value.
  • 5. Cont.. • Example • Duplicate values will be ignored: • thisset = {"apple", "banana", "cherry", "apple"} print(thisset) • Output: {'banana', 'cherry', 'apple’} • Get the Length of a Set • To determine how many items a set has, use the len() function. • A set can contain different data types: • Example • A set with strings, integers and boolean values: • set1 = {"abc", 34, True, 40, "male"} • type() • From Python's perspective, sets are defined as objects with the data type 'set': • <class 'set'>
  • 6. Cont.. • Access Items • You cannot access items in a set by referring to an index or a key. • But you can loop through the set items using a for loop or ask if a specified value is present in a set, by using the in keyword. • Example • Loop through the set, and print the values: • thisset = {"apple", "banana", "cherry"} • for x in thisset: • print(x) • Output: banana • apple • cherry
  • 7. Cont.. • Example • Check if "banana" is present in the set: • thisset = {"apple", "banana", "cherry"} print("banana" in thisset) • Output: True • Change Items • Once a set is created, you cannot change its items, but you can add new items. • Add Items • To add one item to a set, use the add() method. • Example • Add an item to a set, using the add() method: • thisset = {"apple", "banana", "cherry"} • thisset.add("orange") • print(thisset) • Output:{'orange', 'banana', 'cherry', 'apple'}
  • 8. Cont.. • Add Sets • To add items from another set into the current set, use the update() method. • Example • Add elements from tropical into thisset: • thisset = {"apple", "banana", "cherry"} • tropical = {"pineapple", "mango", "papaya"} • thisset.update(tropical) • print(thisset) • Output: {'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}
  • 9. Cont.. • Add Any Iterable • The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.). • Example • Add elements of a list to at set: • thisset = {"apple", "banana", "cherry"} • mylist = ["kiwi", "orange"] • thisset.update(mylist) • print(thisset) • Output: {'banana', 'cherry', 'apple', 'orange', 'kiwi'}
  • 10. Cont.. • Remove Item • To remove an item in a set, use the remove(), or the discard() method. • Example • Remove "banana" by using the remove() method: • thisset = {"apple", "banana", "cherry"} • thisset.remove("banana") • print(thisset) • Output: {'cherry', 'apple’} • Note: If the item to remove does not exist, remove() will raise an error.
  • 11. Cont.. • Example: • thisset = {"apple", "cherry"} • thisset.remove("banana") • print(thisset) • Output: File "./prog.py", line 3, in <module> • KeyError: 'banana’ • Example • Remove "banana" by using the discard() method: • thisset = {"apple", "banana", "cherry"} • thisset.discard("banana") • print(thisset) • Output: {'apple', 'cherry’} • Note: If the item to remove does not exist, discard() will NOT raise an error.
  • 12. Cont.. • You can also use the pop() method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed. • The return value of the pop() method is the removed item. • thisset = {"apple", "banana", "cherry"} x = thisset.pop() print(x) print(thisset) • Output: banana • {'cherry', 'apple’} • Example • The clear() method empties the set: • thisset = {"apple", "banana", "cherry"} • thisset.clear() • print(thisset) • Output: set()
  • 13. Cont.. • Example • The del keyword will delete the set completely: • thisset = {"apple", "banana", "cherry"} • del thisset • print(thisset) • Output: File "demo_set_del.py", line 5, in <module> • print(thisset) #this will raise an error because the set no longer exists • NameError: name 'thisset' is not defined • Python - Loop Sets • Same as in list and tuples
  • 14. Cont.. • Join Two Sets • There are several ways to join two or more sets in Python. • You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another: • Example • The union() method returns a new set with all items from both sets: • set1 = {"a", "b" , "c"} • set2 = {1, 2, 3} • set3 = set1.union(set2) • print(set3) • Output: {'c', 'b', 1, 'a', 2, 3}
  • 15. Cont.. • Example • The update() method inserts the items in set2 into set1: • set1 = {"a", "b" , "c"} • set2 = {1, 2, 3} • set1.update(set2) • print(set1) • Output: {'a', 2, 'c', 1, 3, 'b’} • Note: Both union() and update() will exclude any duplicate items. • Keep ONLY the Duplicates • The intersection_update() method will keep only the items that are present in both sets. • Example • Keep the items that exist in both set x, and set y: • x = {"apple", "banana", "cherry"} • y = {"google", "microsoft", "apple"} • x.intersection_update(y) • print(x) • Output: {'apple'}
  • 16. Cont.. • The intersection() method will return a new set, that only contains the items that are present in both sets. • Example • Return a set that contains the items that exist in both set x, and set y: • x = {"apple", "banana", "cherry"} • y = {"google", "microsoft", "apple"} • z = x.intersection(y) • print(z) • Output: {'apple'}
  • 17. Cont.. • Keep All, But NOT the Duplicates • The symmetric_difference_update() method will keep only the elements that are NOT present in both sets. • Example • Keep the items that are not present in both sets: • x = {"apple", "banana", "cherry"} • y = {"google", "microsoft", "apple"} • x.symmetric_difference_update(y) • print(x) • Output: • {'google', 'banana', 'microsoft', 'cherry'}
  • 18. Cont.. • The symmetric_difference() method will return a new set, that contains only the elements that are NOT present in both sets. • Example • Return a set that contains all items from both sets, except items that are present in both: • x = {"apple", "banana", "cherry"} • y = {"google", "microsoft", "apple"} • z = x.symmetric_difference(y) • print(z) • Output: {'google', 'banana', 'microsoft', 'cherry'}