Python Sets

JK1184 
Created at Jun 15, 2023 09:30:37
Updated at May 09, 2024 16:10:27 
58   0   0   0  

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.

thisset = {"apple", "banana", "cherry"}
print(thisset)

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.


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.


Duplicates Not Allowed

Sets cannot have two items with the same value.

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)
thisset = {"apple", "banana", "cherry", False, True, 0}

print(thisset)

Get the Length of a Set

To determine how many items a set has, use the len() function.

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Set Items - Data Types

Set items can be of any data type:

set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:

set1 = {"abc", 34, True, 40, "male"}

type()

From Python's perspective, sets are defined as objects with the data type 'set':

myset = {"apple", "banana", "cherry"}
print(type(myset))

 

The set() Constructor

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)

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.

thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

Check if "banana" is present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Add Items

To add one item to a set use the add() method.

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Add Sets

To add items from another set into the current set, use the update() method.

thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

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.).

thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Remove Item

To remove an item in a set, use the remove(), or the discard() method.

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)
thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

Loop Items

You can loop through the set items by using a for loop:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

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:

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

Keep ONLY the Duplicates

The intersection_update() method will keep only the items that are present in both sets.

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.

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.intersection(y)

print(z)

Keep All, But NOT the Duplicates

The symmetric_difference_update() method will keep only the elements 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.

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.symmetric_difference(y)

print(z)
x = {"apple", "banana", "cherry", True}
y = {"google", 1, "apple", 2}

z = x.symmetric_difference(y)

print(z)

Set Methods

Python has a set of built-in methods that you can use on sets.

MethodDescription
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


Tags: Python Python Sets Share on Facebook Share on X

◀ PREVIOUS
Python Tuples
▶ NEXT
Python Dictionaries
  Comments 0
Login for comment
SIMILAR POSTS

Python Tuples (updated at May 09, 2024)

Python Dictionaries (updated at May 09, 2024)

Python Comparison Operators (updated at May 10, 2024)

Python Arithmetic Operators (created at Jun 14, 2023)

Python Conditions and If statements (updated at May 09, 2024)

Python Lists (updated at May 10, 2024)

Python String Operations (updated at May 10, 2024)

Python Data Types (updated at May 10, 2024)

Python While Loops/For Loops (updated at May 09, 2024)

Python Functions (updated at May 09, 2024)

Python Variables (updated at May 10, 2024)

Python Comments (updated at May 10, 2024)

Python Syntax (updated at May 10, 2024)

Python Lambda (updated at May 09, 2024)

Python Arrays (updated at May 09, 2024)

Python Classes/Objects (updated at May 09, 2024)

Python Getting Started (updated at May 10, 2024)

Python Introduction (created at Jun 12, 2023)

What is Python? (updated at Jan 04, 2024)

Python Inheritance (updated at May 09, 2024)

Python Iterators (updated at May 09, 2024)

Python Polymorphism (updated at May 09, 2024)

Python Scope (updated at May 09, 2024)

Python Modules (updated at May 09, 2024)

Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering (updated at May 12, 2024)

Machine Learning Types and Programming Languages (updated at Nov 29, 2023)

Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship (updated at May 10, 2024)

Mastering Excel Data Manipulation with Python (updated at Apr 26, 2024)

OTHER POSTS IN THE SAME CATEGORY

Python code to convert from Lunar to Solar (created at Mar 22, 2024)

Python example to download webpage (updated at May 15, 2024)

Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship (updated at May 10, 2024)

Python Modules (updated at May 09, 2024)

Python Scope (updated at May 09, 2024)

Python Polymorphism (updated at May 09, 2024)

Python Iterators (updated at May 09, 2024)

Python Inheritance (updated at May 09, 2024)

Python Classes/Objects (updated at May 09, 2024)

Python Arrays (updated at May 09, 2024)

Python Lambda (updated at May 09, 2024)

Python Functions (updated at May 09, 2024)

Python While Loops/For Loops (updated at May 09, 2024)

Python Conditions and If statements (updated at May 09, 2024)

Python Dictionaries (updated at May 09, 2024)

Python Tuples (updated at May 09, 2024)

Python Comparison Operators (updated at May 10, 2024)

Python Arithmetic Operators (created at Jun 14, 2023)

Python Lists (updated at May 10, 2024)

Python String Operations (updated at May 10, 2024)

Python Data Types (updated at May 10, 2024)

Python Variables (updated at May 10, 2024)

Python Comments (updated at May 10, 2024)

Python Syntax (updated at May 10, 2024)

Python Getting Started (updated at May 10, 2024)

Python Introduction (created at Jun 12, 2023)

What is Python? (updated at Jan 04, 2024)

UPDATES

Aiming for Congressional Award Gold? Your Registration Guide! (created at May 19, 2024)

Digital SAT what you should know (updated at May 17, 2024)

Reflections on a Year of Volunteering at Torrance Wilson Park: Season in 2023-2024 (updated at May 16, 2024)

ChatGPT Reset command and Ignore the Previous Response feature to have a Solid Result (updated at May 16, 2024)

Python example to download webpage (updated at May 15, 2024)

Impact in the theird party cookie on web browser (updated at May 15, 2024)

Why Nike Card Wallets Are a Smart Buy for the Stylishly Practical (updated at May 15, 2024)

How to Rip a Leg that hundreds of people succeeded in (updated at May 15, 2024)

Little Johnny Kang's Taekwondo Journey at the Kukkiwon in 2016 (created at May 15, 2024)

IU's Life Snapshots (updated at May 15, 2024)

Java Tutorials associated with AP Computer Science A (updated at May 15, 2024)

Java Getting Started (updated at May 15, 2024)

Java Syntax (updated at May 15, 2024)

Java Comments (updated at May 15, 2024)

Java Variables (updated at May 15, 2024)

Java Math (updated at May 15, 2024)

Java If ... Else (updated at May 15, 2024)

Java Short Hand If...Else (Ternary Operator) (updated at May 15, 2024)

Java Switch Statements (updated at May 15, 2024)

Loading XML Data with JavaScript (created at May 15, 2024)

Finding Comfort in the Chaos: My LOL Journey on US Servers (updated at May 14, 2024)

Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue (updated at May 13, 2024)

Java Arrays (updated at May 13, 2024)

Meet NewJeans Danielle: The Rising Star with Killer Dance Moves! (updated at May 13, 2024)

IU's 5.16MHz with UAENA (updated at May 12, 2024)

Microsoft Windows commands frquently used (updated at May 12, 2024)

Key Features of the Apache License (updated at May 12, 2024)

Naver Papago - multilingual machine translation service (updated at May 12, 2024)

What is Sitemap? Why do we need it? (updated at May 12, 2024)

What is a smart TV? (updated at May 12, 2024)

Semantic Network - a method of expressing knowledge based on a mesh structure (updated at May 12, 2024)

What is the role of README.md at GitHub/GitLab Repository? (updated at May 12, 2024)

Google Map Link Logic (updated at May 12, 2024)

Flying side kick - Run → Jump → Kick (updated at May 12, 2024)

Las Vegas KÀ by Cirque du Soleil that showed us an exciting fantasy (updated at May 12, 2024)

Physics Areas and Formulas (updated at May 12, 2024)

Statistics Formulas (updated at May 12, 2024)

PreCalculus Formulas for Trigonometry and Math Analysis (updated at May 12, 2024)

Differential/Integral Calculus Formulas (updated at May 12, 2024)

Mean(Averange) and Median based on Global Wealth per Person (updated at May 12, 2024)

Sneaker Style: Perfect Shoes to Wear with Jeans (updated at May 12, 2024)

YouTube Multiview Video Games Dataset from UC Irvine Machine Learning Repository (updated at May 12, 2024)

How to tie your Taekwondo Belt? (updated at May 12, 2024)

Taekwondo Tornado Kick Tutorial - one of my favorite kicks (updated at May 12, 2024)

Exploring the Heartfelt History and Traditions of Valentine's Day (updated at May 12, 2024)

Resell Price $9,400 - Apple Vision Pro Goes Off Right After Launch (updated at May 12, 2024)

Clack Attack - Embracing the Joyful Chaos of Mechanical Keyboards (updated at May 12, 2024)

Indulging in Delight: Waffles and Long Drinks in Seoul, Korea (updated at May 12, 2024)

A House Tour Adventure in the California, US (updated at May 12, 2024)

Base camp for house hunting in Anaheim near Disney Land (updated at May 12, 2024)