Tuesday , March 19 2024
Python Date and Time - Getting Current Date and Time, What is Tick & Get Calendar For a month

Python Sets

Python Sets

Python Set

A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed).

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. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.

A set is a collection which is both unordered and unindexed. Sets are written with curly brackets {}

In [1]:
my_set = {"python", "data science", "machine learning"}
print(my_set)
{'python', 'data science', 'machine learning'}

set of mixed datatypes

In [2]:
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
{1.0, (1, 2, 3), 'Hello'}
  • Set items are unordered, unchangeable, and do not allow duplicate values.
  • Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
  • Sets are unchangeable, meaning that we cannot change the items after the set has been created.

Duplicates Not Allowed

In [3]:
my_set = {"python", "data science", "machine learning","python"}
print(my_set)
{'python', 'data science', 'machine learning'}

Get the Length and Type of a Set

In [4]:
my_set = {"python", "data science", "machine learning"}
print(len(my_set))
3
In [5]:
print(type(my_set))
<class 'set'>

Access Set 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.
In [6]:
my_set = {"python", "data science", "machine learning"}
for item in my_set:
    print(item)
python
data science
machine learning

Add Set Items

  • Once a set is created, you cannot change its items, but you can add new items using the add() method
In [7]:
my_set = {"Python", "Data Science", "Machine Learning"}
my_set.add("Deep Learning")
print(my_set)
{'Python', 'Machine Learning', 'Data Science', 'Deep Learning'}

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

In [8]:
my_set1 = {"apple", "kiwi", "cherry"}
my_set2 = {"pineapple", "mango", "orange"}

my_set1.update(my_set2)

print(my_set1)
{'orange', 'mango', 'pineapple', 'kiwi', 'cherry', 'apple'}

Add Any Iterable object (tuples, lists, dictionaries etc.).

In [9]:
my_set1 = {"apple", "kiwi", "cherry"}
my_set2 = ["pineapple", "mango", "orange"]

my_set1.update(my_set2)

print(my_set1)
{'orange', 'mango', 'pineapple', 'apple', 'kiwi', 'cherry'}

Remove Set Items

  • To remove an item in a set, use the remove(), or the discard() method.
In [10]:
print(my_set1)
{'orange', 'mango', 'pineapple', 'apple', 'kiwi', 'cherry'}
In [11]:
my_set1.remove("cherry")
print(my_set1)
{'orange', 'mango', 'pineapple', 'apple', 'kiwi'}
In [12]:
my_set1.discard("apple")
print(my_set1)
{'orange', 'mango', 'pineapple', 'kiwi'}

Note: If the item to remove does not exist, discard() will NOT raise an error.

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.

In [13]:
my_set = {"Python", "Data Science", "Machine Learning"}
my_set.pop()
print(my_set)
{'Machine Learning', 'Data Science'}

The clear() method empties the set:

In [14]:
my_set = {"Python", "Data Science", "Machine Learning"}
my_set.clear()
print(my_set)
set()

The del keyword will delete the set completely:

In [15]:
my_set = {"Python", "Data Science", "Machine Learning"}
del my_set
print(my_set)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-15-fd49edf7af8b> in <module>
      1 my_set = {"Python", "Data Science", "Machine Learning"}
      2 del my_set
----> 3 print(my_set)

NameError: name 'my_set' is not defined

Loop Items

  • You can loop through the set items by using a for loop:
In [16]:
my_set = {"Python", "Data Science", "Machine Learning"}
for item in my_set:
    print(item)
Python
Machine Learning
Data Science

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:
In [17]:
set1 = {"apple", "kiwi", "cherry"}
set2 = {"pineapple", "mango", "orange"}

set3 = set1.union(set2)
print(set3)
{'orange', 'mango', 'pineapple', 'kiwi', 'cherry', 'apple'}
In [18]:
set1 = {"apple", "kiwi", "cherry"}
set2 = {"pineapple", "mango", "orange"}

set1.update(set2)
print(set1)
{'orange', 'mango', 'pineapple', 'kiwi', 'cherry', 'apple'}

Note: Both union() and update() will exclude any duplicate items.

Keep ONLY the Duplicates

  • The intersection_update() method will keep only the items that are present in both sets.
In [19]:
set1 = {"apple", "kiwi", "cherry"}
set2 = {"pineapple", "mango", "apple"}

set1.intersection_update(set2)
print(set1)
{'apple'}

Keep All, But NOT the Duplicates

  • The symmetric_difference_update() method will keep only the elements that are NOT present in both sets.
In [20]:
set1 = {"apple", "kiwi", "cherry"}
set2 = {"pineapple", "mango", "apple"}

set1.symmetric_difference_update(set2)
print(set1)
{'cherry', 'mango', 'pineapple', 'kiwi'}

The symmetric_difference() method will return a new set, that contains only the elements that are NOT present in both sets.

In [21]:
set1 = {"apple", "kiwi", "cherry"}
set2 = {"pineapple", "mango", "apple"}

set3 = set1.symmetric_difference(set2)
print(set3)
{'mango', 'pineapple', 'kiwi', 'cherry'}

About Machine Learning

Check Also

Python MySQL Insert Into Table

Python MySQL Insert Into Table

4 Python MySQL Insert Into Table Python MySQL Insert Into Table¶To fill a table in …

Leave a Reply

Your email address will not be published. Required fields are marked *