Python Sets


Set

Multiple items are being stored in a single variable using sets.

A set is an unsorted and unindexed collection of items.

Curly brackets {} are used to write sets.

Example :- Create a Set :

myset = {"html", "css", "java"}
print(myset)

# Note: the set list is unordered, meaning: the items will appear in a random order.

# Refresh this page to see the change in the result.

Output :-

{'html', 'css', 'java'}

Note : Sets are not arranged, so you can't be sure the items are shown in which order.

Note : If you run the program multiple times, you can see different result.

You can also search for these topics, mutable sets in python, define the functions using python, python union sets, what is dictionaries with python sets, what's the difference between lists vs sets in python, how to create the sets in python, Example for python sets.

Set Items

Unordered unchangeable items are specified and Duplicate values are not permitted.

You can also search for these topics, what are python set items, python set add multiple items, how to add list of set items in python, python set to remove multiple items, ways to get set items using python, sort the set items for python, python to count the python set items.

Unordered

Unordered means that the items in a set have no specific order.

Set items can be displayed by index or key in a different order each time you use them.

You can also search for these topics, how to set unordered in python, how to set intersection with python, what is the frozen set in python, python add the ordered sets, list the python unordered sets.

Unchangeable

Sets cannot be modified, which means that after the set is created, we cannot change items.

You cannot modify the existing items once a set is created, but new items can also be added.

You can also search for these topics, python set unchangable, how to create the python set unchangable, python key object and value unchanged, what are the methods available in python unchangable, how to add new items in python unchangable.

Duplicates Not Allowed

Sets can't possess the same value for two items. Duplicate values are ignored by sets.

Example :- A simple set with duplicate values :

myset = {"html", "css", "java", "html"}

print(myset)

Output :-

{'html', 'css', 'java'}

You can also search for these topics, python set duplicates not allowed, verify the two items in python set duplicates, allow the python set duplicates, define the same values with python set, Example for python duplicates not allowed.

Get the Length of a Set

Use the len() method to figure out how many objects has set.

Example :- Get the number of items in a set :

myset = {"html", "css", "java"}

print(len(myset))

Output :-

3

You can also search for these topics, python get the length of a set, python len() method, how many items to get the length of a set in python, Example for python get the length of a set, list to get the length of a set using python.

Set Items - Data Types

Any data type can be used to set items :

Example 1 :- Creating multiple sets with various types like string, int and boolean :

set1 = {"html", "css", "java"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False}

print(set1)
print(set2)
print(set3)

Output :-

{'html', 'css', 'java'}
{1, 3, 5, 7, 9}
{False, True}

Various data types can be found in a set:

Example 2 :- A single set with different datatypes like strings, integers and boolean values :

set1 = {111, "abc", 4.2, True}

print(set1)

Output :-

{111, True, 4.2, 'abc'}

You can also search for these topics, set items data type in python, how set items are different data types in python, python list the set items with datatypes, example for python set items with data types.

type()

Sets are objects with the data type 'set' in Python :

<class 'set'>

Example :- What is the data type of a set?

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

print(type(myset))

Output :-

<class 'set'>

You can also search for these topics, python set type() not working , return value of python type, python set type arguments, type the builtin using python type, how to change the type in python set, comparison of python set type, check the type of python sets, python set keyerror type, Example for type of set using python, What is the data type of a python sets?.

The set() Constructor

The set() constructor can also be used to create a set.

Example :- Using the set() constructor to make a set :

myset = set(("a", "b", "c"))
print(myset)

# Note: the set list is unordered, so the result will display the items in a random order.

Output :-

{'c', 'b', 'a'}

You can also search for these topics, python set() constructor, set constructor string in python, how to set the property and value with python constructor, set the static and dynamic python constructor, python set class constructor, Example for python set constructor.

Python - Access Set Items

Python provides readonly access to an set.

Access Items

An index or a key can't be used to access the elements in a set.

The in keyword allows you to ask if a specific value is present in a set by looping through the items in the set using the for loop.

Example 1 :- Print all values from a set using for loop :

myset = {"html", "css", "java"}

for x in myset:
  print(x)

Output :-

html
css
java

Example 2 :- Check to see if the word "java" is in the set :

myset = {"html", "css", "java"}

print("java" in myset)

Output :-

True

You can also search for these topics, how to access item in set python, access first item in set python, python access set item does not support item assignment, Example for python access set items.

Change Items

The items in a set can't be changed once it's been formed, but you can add new items.

You can also search for these topics, python change item in set, python change item set with another set, change item set python add difference, change item set python example.

Python - Add Set Items

The items in a set can't be changed once it's been formed, but you can add new items.

Add New Items

Use the add() method to add one item to a set :

Example :- Add a new item to set:

myset = {"html", "css", "java"}

myset.add("python")

print(myset)

Output :-

{'html', 'css', 'python', 'java'}

You can also search for these topics, python set add multiple item, python set add multiple element at once, add set item python dupliicate error, add set item python existing, Example for python Add Items.

Add Sets

Using the update() method, you can add items from another set to the current set.

Example :- Add elements from myset2 into myset :

myset = {"html", "css", "java"}
myset2 = {"jquery", "nodejs"}

myset.update(myset2)

print(myset)

Output :-

{'css', 'jquery', 'nodejs', 'html', 'java'}

You can also search for these topics, python add multiple sets, can you add sets in python, python set add and remove, can we add two sets in python, python set add not working, Example for python Add Sets.

Add Any Iterable

When using the update() method, the object in question doesn't have to be a set, but rather, any iterable object (tuples, lists, dictionaries etc.).

Example :- Add a list to set

myset = {"html", "css", "java"}
mylist = ["c", "cpp"]

myset.update(mylist)

print(myset)

Output :-

{'css', 'html', 'cpp', 'java', 'c'}

You can also search for these topics, python add any iterable set by value, python set add any iterable function, set add any iterable python meaning, set add any iterable python example.

Python - Remove Set Items

Use the remove() or discard() methods to remove an item from a set.

The remove() method will throws an error, if the item not found.

The discard() method will not raise any error, if the item not found.

Example 1 :- Using the remove() method, remove "java" from the set :

myset = {"html", "css", "java"}

myset.remove("java")

print(myset)

Output :-

{'html', 'css'}

Note :- The remove() function throws an error if the item doesn't exist.

Example 2 :- Use the discard() function to remove "css" :

myset = {"html", "css", "java"}

myset.discard("css")

print(myset)

Output :-

{'html', 'java'}

Note : If the object to be removed doesn't exist, discard() will not raise an error.

The pop() method can also be used to delete an item, however it will only remove the final item. Recall that sets are unordered, thus you won't be able to tell which item has been deleted.

The removed item is returned as a result of the pop() method's return value.

Example 3 :- The pop() method can be used to remove the last item :

myset = {"html", "css", "java"}

x = myset.pop()

print(x) #removed item

print(myset) #the set after removal

Output :-

css
{'html', 'java'}

Note : If you use the pop() method, you won't know which item has been removed because sets are unordered.

Example 4 :- Using the clear() method, the set is emptied of its contents :

myset = {"html", "css", "java"}

myset.clear()

print(myset)

Output :-

set()

Example 5 :- With the del keyword, the entire set will be removed :

myset = {"html", "css", "java"}

del myset

print(myset) #this will raise an error because the set no longer exists

Output :-

Traceback (most recent call last):
File "demo_set_del.py", line 5, in < module>
print(myset) #this will raise an error because the set no longer exists
NameError: name 'myset' is not defined

You can also search for these topics, python remove item from set while iterating, how to remove an item from a set in python, python set remove all element, write a python program to remove items from set, python set remove all elements, Example for python remove set items.

Python - Loop Sets

Using a for loop, you may loop through the set elements :

Example :- Using a for loop, print out the values in the set :

myset = {"html", "css", "java"}

for x in myset:
  print(x)

Output :-

html
css
java

You can also search for these topics, python loop over sets elements, python loop set item previous, loop through list and remove items python, loop set item python range, Example for python loop sets.

Python - Join Sets

Two or more sets can be joined in a variety of ways in Python.

Join Two Sets

You can use the union() method, which returns a new set containing all items from both sets, or the update() method, which updates all items from one set into another :

Example 1 :- All elements from both sets are returned by the union() method :

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

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

Output :-

{'a', 'b', 3, 2, 1, 'c'}

Example 2 :- As a result of calling update(), the items from Set2 are inserted into Set1 :

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

set1.update(set2)
print(set1)

Output :-

{1, 3, 'b', 'c', 2, 'a'}

Note :- It's important to note that both union() and update() will remove any duplicates.

You can also search for these topics, python join two set together, merge two dataset in python, python union between two sets, python join two sets keys to same value, Example for python join two sets.

Keep ONLY the Duplicates

By default, only the items that appear in both sets are kept by intersection_update().

Example 1 :- Retain the items that appear in both x and y sets :

x = {"a", "b", "c"}
y = {"a", "c", "d"}

x.intersection_update(y)

print(x)

Output :-

{'a', 'c'}

Using the intersection() technique, you'll get a new set containing only the elements that are in both sets.

Example 2 :- Return a set that contains the items that exist in both set x, and set y :

x = {"a", "b", "c"}
y = {"a", "c", "d"}

z = x.intersection(y)

print(z)

Output :-

{'a', 'c'}

You can also search for these topics, how to keep only duplicates python, python keep only duplicates given sentence, python keep only duplicates observation, keep only duplicates python words from a given sentence, Example for python Keep ONLY the Duplicates.

Keep All, But NOT the Duplicates

When using the symmetric_difference_update() technique, only the elements that NOT present in both sets will be kept.

Example 1 :- Keep the items that are not present in both sets :

x = {"a", "b", "c"}
y = {"a", "c", "d"}

x.symmetric_difference_update(y)

print(x)

Output :-

{'b', 'd'}

With this procedure, you will get a new set that only contains the components that are NOT present in both sets.

Example 2 :- You'll get back a set that has all things from both sets, excluding those that are in both sets :

x = {"a", "b", "c"}
y = {"a", "c", "d"}

z = x.symmetric_difference(y)

print(z)

Output :-

{'b', 'd'}

You can also search for these topics, python keep all but not duplicates same value, keep all but not duplicates python error, Example for Keep All, But NOT the Duplicates.