Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
HowToDoInJava
  • Java
  • Spring AI
  • Spring Boot
  • Hibernate
  • JUnit 5
  • Interview

Python Set

Python Sets are unordered collections of unique elements. Learn about Set datatype in Python, creating and modifying Sets and other useful Set operations available. 1. What is Set A Set in Python is: an unordered collection of unique hashable objects unindexed collection written with curly brackets or set() …

Lokesh Gupta

October 1, 2022

Python Datatypes
Python Basics
Python

Python Sets are unordered collections of unique elements. Learn about Set datatype in Python, creating and modifying Sets and other useful Set operations available.

1. What is Set

A Set in Python is:

  • an unordered collection of unique hashable objects
  • unindexed collection
  • written with curly brackets or set() constructor
# curly brackets
nameSet = {"alex", "brian", "charles"}

# set() constructor
nameSet = set(("alex", "brian", "charles"))

Internally, the Set is implemented using Dictionary. If we notice closely, the requirements for Set elements are the same as those for Dictionary keys.

Sets cannot store mutable items such as List or Dictionary. However, Sets can contain immutable collections such as Tuple or instances of ImmutableSet.

2. Get Values from Set

2.1. Iterate Set using for Loop

As Sets are unindexed collection, we cannot use index-based get operations and slicing operations. So, to get the values from a Set, we can loop through it using for loop.

nameSet = {"alex", "brian", "charles"}
for name in nameSet:
  	print(name)

Program output.

alex
brian
charles

2.2. Check Item Exists using in Clause

nameSet = {"alex", "brian", "charles"}

print("brian" in nameSet)
print("david" in nameSet)

Program output.

True
False

3. Add Items in Sets

  • To add a new item to the Set, use the add() method.
  • To add more than one item to the Set, use the update() method.
nameSet = {"alex", "brian", "charles"}

nameSet.add("david")
print(nameSet)

nameSet.update(["evan", "frank", "george"])
print(nameSet)

Program output.

{'alex', 'charles', 'brian', 'david'}
{'brian', 'alex', 'david', 'frank', 'george', 'charles', 'evan'}

4. Remove Items from Set

To remove a single item from the Set, we can use following methods:

  • remove() : If the item to remove does not exist, it will raise an error.
  • discard() : If the item to remove does not exist, it will NOT raise an error.
  • pop() : This method will remove the last item in the Set, and removed item will be the return valve of the method call.
  • clear() : It removes ann the items from the Set, and converts the set to an Empty Set.
  • del keyword : It delete the Set completely.
nameSet = {"alex", "brian", "charles", "evan", "frank"}

nameSet.remove("frank")
print(nameSet)

nameSet.discard("evan")
print(nameSet)

name = nameSet.pop()
print(name)
print(nameSet)

nameSet.clear()
print(nameSet)

del nameSet
print(nameSet)

Program output.

{'evan', 'alex', 'charles', 'brian'}

{'alex', 'charles', 'brian'}

alex
{'charles', 'brian'}

set()

Traceback (most recent call last):
  File "<string>", line 17, in <module>
NameError: name 'nameSet' is not defined

5. Set Union – Join Two Sets

Use the union() method to join two or more sets in Python. This method returns a new Set containing all items from both Sets.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"evan", "frank"}

setUnion = nameSet1.union(nameSet2)
print(setUnion)

Program output.

{'charles', 'frank', 'alex', 'evan', 'brian'}

6. Python Set Methods

Python Set provides following built-in methods:

6.1. Python Set add()

The add() method adds an item to the Set.

nameSet = {"alex", "brian", "charles"}

nameSet.add("david")
print(nameSet)

Program output.

{'alex', 'brian', 'charles', 'david'}

6.2. Python Set clear()

The clear() method removes all the items from the Set, and make it empty Set.

nameSet = {"alex", "brian", "charles"}

nameSet.clear()
print(nameSet)

Program output.

set()

6.3. Python Set copy()

The copy() method returns a shallow copy of the Set.

nameSet = {"alex", "brian", "charles"}

copySet = nameSet.copy()
print(copySet)

Program output.

{'alex', 'brian', 'charles'}

6.4. Python Set difference()

The difference() method returns a Set containing the difference between two Sets.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"alex", "brian", "david"}

diffSet = nameSet1.difference(nameSet2)
print(diffSet)

Program output.

{'charles'}

6.5. Python Set difference_update()

The difference_update() method removes the items in given set that are also included in argument Set.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"alex", "brian", "david"}

nameSet1.difference_update(nameSet2)
print(nameSet1)

Program output.

{'charles'}

6.6. Python Set discard()

The discard() method removes the specified item from the Set.

nameSet = {"alex", "brian", "charles"}

nameSet.discard("charles")
print(nameSet)

Program output.

{'alex', 'brian'}

6.7. Python Set intersection()

The intersection() method returns a Set which is intersection of two given Sets. This method is opposite to the difference() method.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"alex", "brian", "david"}

diffSet = nameSet1.intersection(nameSet2)
print(diffSet)

Program output.

{'alex', 'brian'}

6.8. Python Set intersection_update()

The intersection_update() removes the items in the given Set that are not present in the argument Set. This method is opposite to the difference_update() method.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"alex", "brian", "david"}

nameSet1.intersection_update(nameSet2)
print(nameSet1)

Program output.

{'alex', 'brian'}

6.9. Python Set isdisjoint()

The isdisjoint() method checks if two Sets have an intersection or not. It returns True if none of the items are present in both Sets, otherwise it returns False.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"alex", "brian", "david"}

result = nameSet1.isdisjoint(nameSet2)
print(result)

Program output.

False

6.10. Python Set issubset()

The issubset() method checks whether argument Set contains this Set or not.

nameSet1 = {"alex", "brian"}
nameSet2 = {"alex", "brian", "charles"}

result = nameSet1.issubset(nameSet2)
print(result)

Program output.

True

6.11. Python Set issuperset()

The issuperset() method checks whether this Set contains argument Set or not.

nameSet1 = {"alex", "brian"}
nameSet2 = {"alex", "brian", "charles"}

result = nameSet1.issuperset(nameSet2)
print(result)

Program output.

False

6.12. Python Set pop()

The pop() method removes and returns the last items from the Set.

nameSet = {"alex", "brian", "charles"}

print(nameSet.pop())
print(nameSet)

Program output.

alex
{'charles', 'brian'}

6.13. Python Set remove()

The remove() method removes the specified from the Set.

nameSet = {"alex", "brian", "charles"}

nameSet.remove("alex")
print(nameSet)

Program output.

{'charles', 'brian'}

6.14. Python Set symmetric_difference()

The symmetric_difference() method return a Set that contains all items from both Sets, except items that are present in both Sets.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"alex", "brian", "david"}

result = nameSet1.symmetric_difference(nameSet2)
print(result)

Program output.

{'david', 'charles'}

6.15. Python Set symmetric_difference_update()

The symmetric_difference_update() method removes the items in this Set that are present in both Sets. It also inserts the items that are not present in both Sets.
.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"alex", "brian", "david"}

nameSet1.symmetric_difference_update(nameSet2)
print(nameSet1)

Program output.

{'david', 'charles'}

6.16. Python Set union()

The union() method return a Set containing the union of both Sets.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"alex", "brian", "david"}

result = nameSet1.union(nameSet2)
print(result)

Program output.

{'alex', 'brian', 'david', 'charles'}

6.17. Python Set update()

The update() method update the given Set with the union of this set and other Set.

nameSet1 = {"alex", "brian", "charles"}
nameSet2 = {"alex", "brian", "david"}

nameSet1.update(nameSet2)
print(nameSet1)

Program output.

{'alex', 'brian', 'david', 'charles'}

Happy Learning !!

Comments

Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Python Tutorial

  • Python Introduction
  • Python Install in Sublime
  • Python Keywords
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Type Conversion
  • Python Examples

Python Flow Control

  • Python if…else
  • Python for Loop
  • Python while Loop
  • Python break
  • Python continue
  • Python pass

Python Datatypes

  • Python Integer
  • Python String
  • Python List
  • Python Tuple
  • Python Set
  • Python Dictionary
  • Python OrderedDict
  • Python Priority Queue

Python Modules

  • Python Bcrypt
  • Python Hashlib
  • Python Httplib2
  • Python JSON

Python Advanced Topics

  • Python CSV Files
  • Building a Recommendation System

Python Reference

  • Built-in Functions
  • String Functions

Table of Contents

  • 1. What is Set
  • 2. Get Values from Set
      • 2.1. Iterate Set using for Loop
      • 2.2. Check Item Exists using in Clause
  • 3. Add Items in Sets
  • 4. Remove Items from Set
  • 5. Set Union – Join Two Sets
  • 6. Python Set Methods
      • 6.1. Python Set add()
      • 6.2. Python Set clear()
      • 6.3. Python Set copy()
      • 6.4. Python Set difference()
      • 6.5. Python Set difference_update()
      • 6.6. Python Set discard()
      • 6.7. Python Set intersection()
      • 6.8. Python Set intersection_update()
      • 6.9. Python Set isdisjoint()
      • 6.10. Python Set issubset()
      • 6.11. Python Set issuperset()
      • 6.12. Python Set pop()
      • 6.13. Python Set remove()
      • 6.14. Python Set symmetric_difference()
      • 6.15. Python Set symmetric_difference_update()
      • 6.16. Python Set union()
      • 6.17. Python Set update()
Photo of author

Lokesh Gupta

A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies. An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Follow on Twitter Portfolio

Previous

Python Dictionary

Next

Python if … elif … else Statements

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

OOP

Regex

Maven

Logging

TypeScript

Python

Meta Links

About Us

Advertise

Contact Us

Privacy Policy

Our Blogs

REST API Tutorial

Follow On:

  • Github
  • LinkedIn
  • Twitter
  • Facebook
Copyright © 2026 | Sitemap