-
Notifications
You must be signed in to change notification settings - Fork 4
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
, andDictionary
, all with different qualities and usage.A set is a collection which is unordered, unchangeable*, and unindexed and do not allow duplicate values. Sets are written with curly brackets.
Create a Set:
this_set1 = set()
this_set2 = {"apple", "banana", "cherry"}
It is also possible to use the
set()
constructor to make a set.
Using the set() constructor to make a set:
this_set = set(("apple", "banana", "cherry")) # note the double round-brackets
print(this_set)
Note: Set items are unchangeable, but you can remove items and add new items.
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Set items are unordered, unchangeable, and do not allow duplicate values.
'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.
Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Sets cannot have two items with the same value.
Duplicate values will be ignored:
this_set = {"apple", "banana", "cherry", "apple"}
print(this_set)
Set items can be of any data type.
String, int and boolean data types:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}
sets are an easy eay to remove duplicates from a collection.
To determine how many items a set has, use the
len()
function.
Get the number of items in a set:
this_set = {"apple", "banana", "cherry"}
print(len(this_set))
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
What is the data type of a set?
this_set = {"apple", "banana", "cherry"}
print(type(this_set))
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 thein
keyword.
Loop through the set, and print the values:
this_set3 = {"apple", "banana", "cherry"}
for x in this_set3:
print(x)
Check if "banana" is present in the set:
this_set4 = {"apple", "banana", "cherry"}
print("banana" in this_set4)
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the
add()
method:
this_set5 = {"apple", "banana", "cherry"}
this_set5.add("orange")
print(this_set5)
To add items from another set into the current set, use the
update()
method.
Add elements from tropical into this_set:
this_set5 = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
this_set5.update(tropical)
print(this_set5)
The object in the
update()
method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).
Add elements of a list to at set:
this_set6 = {"apple", "banana", "cherry"}
my_list = ["kiwi", "orange"]
this_set6.update(my_list)
print(this_set6)
To remove an item in a set, use the
remove()
, or thediscard()
method.
Note: If the item to remove does not exist,
remove()
will raise an error.
Remove "banana" by using the remove()
method:
this_set = {"apple", "banana", "cherry"}
this_set.remove("banana")
print(this_set)
Note: If the item to remove does not exist,
discard()
will NOT raise an error.
Remove "banana" by using the discard()
method:
this_set = {"apple", "banana", "cherry"}
this_set.discard("banana")
print(this_set)
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.
this_set = {"apple", "banana", "cherry"}
x = this_set.pop()
print(x)
print(this_set)
The
clear()
method empties the set:
this_set9 = {"apple", "banana", "cherry"}
this_set9.clear()
print(this_set9)
The del keyword will delete the set completely:
this_set = {"apple", "banana", "cherry"}
del this_set
print(this_set)
You can loop through the set items by using a for loop.
Loop through the set, and print the values:
this_set11 = {"apple", "banana", "cherry"}
for x in this_set11:
print(x)
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 theupdate()
method that inserts all the items from one set into another.
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)
# or
print(set1 | set2)
The update()
method inserts the items in set2 into set1:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Note: Both union() and update() will exclude any duplicate items.
The
intersection_update()
method will keep only the items that are present in both sets.
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)
The
intersection()
method will return a new set, that only contains the items that are present in both sets.
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)
# or
print(x & y)
The
symmetric_difference_update()
method will keep only the elements that are NOT present in both sets.
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)
The
symmetric_difference()
method will return a new set, that contains only the elements that are NOT present in both sets.
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)
difference
-
: returns new set with members from left not in right.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
print(x - y)
Python has a set of built-in methods that you can use on sets.
add()
: Adds an element to the set.
clear()
: Removes all the elements from the set.
copy()
: Returns a copy of the set.
difference()
: Returns a set containing the difference between two or more sets.
difference_update()
: Removes the items in this set that are also included in another, specified set.
discard()
: Remove the specified item.
intersection()
: Returns a set, that is the intersection of two other sets.
intersection_update()
: Removes the items in this set that are not present in other, specified set(s).
isdisjoint()
: Returns whether two sets have a intersection or not.
issubset()
: Returns whether another set contains this set or not.
issuperset()
: Returns whether this set contains another set or not.
pop()
: Removes an element from the set.
remove()
: Removes the specified element.
symmetric_difference()
: Returns a set with the symmetric differences of two sets.
symmetric_difference_update()
: inserts the symmetric differences from this set and another.
union()
: Return a set containing the union of sets.
update()
: Update the set with the union of this set and others.
print({1, 2, 3} is {1, 2, 3}) # output: False
print({1, 2, 3} == {1, 2, 3}) # output: True
- Introduction
- Variables
- Data Types
- Numbers
- Casting
- Strings
- Booleans
- Operators
- Lists
- Tuple
- Sets
- Dictionaries
- Conditionals
- Loops
- Functions
- Lambda
- Classes
- Inheritance
- Iterators
- Multi‐Processing
- Multi‐Threading
- I/O Operations
- How can I check all the installed Python versions on Windows?
- Hello, world!
- Python literals
- Arithmetic operators and the hierarchy of priorities
- Variables
- Comments
- The input() function and string operators
Boolean values, conditional execution, loops, lists and list processing, logical and bitwise operations
- Comparison operators and conditional execution
- Loops
- [Logic and bit operations in Python]
- [Lists]
- [Sorting simple lists]
- [List processing]
- [Multidimensional arrays]
- Introduction
- Sorting Algorithms
- Search Algorithms
- Pattern-matching Algorithm
- Graph Algorithms
- Machine Learning Algorithms
- Encryption Algorithms
- Compression Algorithms
- Start a New Django Project
- Migration
- Start Server
- Requirements
- Other Commands
- Project Config
- Create Data Model
- Admin Panel
- Routing
- Views (Function Based)
- Views (Class Based)
- Django Template
- Model Managers and Querysets
- Form
- User model
- Authentification
- Send Email
- Flash messages
- Seed
- Organize Logic
- Django's Business Logic Services and Managers
- TestCase
- ASGI and WSGI
- Celery Framework
- Redis and Django
- Django Local Network Access
- Introduction
- API development
- API architecture
- lifecycle of APIs
- API Designing
- Implementing APIs
- Defining the API specification
- API Testing Tools
- API documentation
- API version
- REST APIs
- REST API URI naming rules
- Automated vs. Manual Testing
- Unit Tests vs. Integration Tests
- Choosing a Test Runner
- Writing Your First Test
- Executing Your First Test
- Testing for Django
- More Advanced Testing Scenarios
- Automating the Execution of Your Tests
- End-to-end
- Scenario
- Python Syntax
- Python OOP
- Python Developer position
- Python backend developer
- Clean Code
- Data Structures
- Algorithms
- Database
- PostgreSQL
- Redis
- Celery
- RabbitMQ
- Unit testing
- Web API
- REST API
- API documentation
- Django
- Django Advance
- Django ORM
- Django Models
- Django Views
- Django Rest Framework
- Django Rest Framework serializers
- Django Rest Framework views
- Django Rest Framework viewsets