Sets Flashcards
What is a set
a set is an unordered collection of unique elements. Sets are very useful for storing and manipulating collections of data, especially when you want to eliminate duplicates or check for membership.
Create a set:
Sets are written with curly brackets.
thisset = {“apple”, “banana”, “cherry”}
print(thisset)
Set intersection
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)
Are sets ordered
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
Are sets changeable
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.
Do sets have duplicate values
Set items are unordered, unchangeable, and do not allow duplicate values.
Duplicate values will be ignored:
Get the Length of a Set
use the len() function.
thisset = {“apple”, “banana”, “cherry”}
print(len(thisset))
Set Items - Data Types
Set items can be of any data type:
Example
String, int and boolean data types:
set1 = {“apple”, “banana”, “cherry”}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
A set can contain different data types:
Example
A set with strings, integers and boolean values:
set1 = {“abc”, 34, True, 40, “male”}
How to you turn data into a set:
It is also possible to use the set() constructor to make a set.
thisset = set((“apple”, “banana”, “cherry”)) # note the double round-brackets
print(thisset)