Python Set and Booleans With Syntax and Examples
Python Set and Booleans With Syntax and Examples
We will understand that as we get deeper into the article with the Python set
Examples.
>>> a={1,3,2}
As you can see, we wrote it in the order 1, 3, 2. In point b, we will access this
set and see what we get back.
>>> c={1,2.0,'three'}
a. Duplicate Elements
A set also cannot contain duplicate elements. Let’s try adding duplicate
elements to another set, and then access it in point b.
>>> b={3,2,1,2}
b. Mutability
A set is mutable, but may not contain mutable items like a list, set, or even a
dictionary.
>>> d={[1,2,3],4}
Output
Traceback (most recent call last):File “<pyshell#9>”, line 1, in
<module>d={[1,2,3],4}
>>> d={{1,3,2},4}
Output
Traceback (most recent call last):File “<pyshell#10>”, line 1, in <module>
d={{1,3,2},4}
>>> d=set()
>>> type(d)
Output
<class ‘set’>
This creates an empty set object. Remember that if you declare an empty set as
the following code, it is an empty dictionary, not an empty set. We confirm
this using the type() function.
>>> d={}
>>> type(d)
Output
<class ‘dict’>
The set() function may also take one argument, however. It should be an
iterable, like a list.
>>> d=set([1,3,2])
>>> a
Output
{1, 2, 3}
Did you see how it reordered the elements into an ascending order? Now let’s
try accessing the set c.
>>> c
Output
{1, 2.0, ‘three’}
>>> b
Output
{1, 2, 3}
As you can see, we had two 2s when we declared the set, but now we have only
one, and it automatically reordered the set.
Also, since sets do not support indexing, they cannot be sliced. Let’s try slicing
one.
>>> b[1:]
Output
Traceback (most recent call last):File “<pyshell#26>”, line 1, in <module>
b[1:]
A method must be called on a set, and it may alter the set. For the following
examples, let’s take a set called numbers.
>>> numbers={3,2,1,4,6,5}
>>> numbers
Output
{1, 2, 3, 4, 5, 6}
a. discard()
This method takes the item to delete as an argument.
>>> numbers.discard(3)
>>> numbers
Output
{1, 2, 4, 5, 6}
As you can see in the resulting set, the item 3 has been removed.
b. remove()
Like the discard() method, remove() deletes an item from the set.
>>> numbers.remove(5)
>>> numbers
Output
{1, 2, 4, 6}
discard() vs remove()-
These two methods may appear the same to you, but there’s actually a
difference.
If you try deleting an item that doesn’t exist in the set, discard() ignores it, but
remove() raises a KeyError.
>>> numbers.discard(7)
>>> numbers
Output
{1, 2, 4, 6}
>>> numbers.remove(7)
Output
Traceback (most recent call last):File “<pyshell#37>”, line 1, in <module>
numbers.remove(7)
KeyError: 7
c. pop()
Like on a dictionary, you can call the pop() method on a set. However, here, it
does not take an argument.
>>> numbers.pop()
Output
1
>>> numbers.pop()
Output
2
>>> {2,1,3}.pop()
Output
1
d. clear()
Like the pop method(), the clear() method for a dictionary can be applied to a
Python set as well. It empties the set in Python.
>>> numbers.clear()
>>> numbers
Output
set()
>>> numbers={3,1,2,4,6,5}
>>> numbers[3]
Output
Traceback (most recent call last):File “<pyshell#56>”, line 1, in <module>
numbers[3]
So, we use two methods for this purpose- add() and update(). We have seen
the update() method on tuples, lists, and strings.
a. add()
It takes as argument the item to be added to the set.
>>> numbers.add(3.5)
>>> numbers
Output
{1, 2, 3, 4, 5, 6, 3.5}
If you add an existing item in the set, the set remains unaffected.
>>> numbers.add(4)
>>> numbers
Output
{1, 2, 3, 4, 5, 6, 3.5}
b. update()
This method can add multiple items to the set at once, which it takes as
arguments.
>>> numbers.update([7,8],{1,2,9})
>>> numbers
Output
{1, 2, 3, 4, 5, 6, 3.5, 7, 8, 9}
>>> days={'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'}
a. len()
The len() function returns the length of a set. This is the number of elements
in it.
>>> len(days)
Output
7
b. max()
This function returns the item from the set with the highest value.
>>> max({3,1,2})
Output
3
>>> max(days)
Output
‘Wednesday’
The Python function returned ‘Wednesday’ because W has the highest ASCII
value among M, T, W, F, and S.
>>> max({1,2,'three','Three'})
Output
Traceback (most recent call last):File “<pyshell#69>”, line 1, in <module>
max({1,2,’three’,’Three’})
c. min()
Like the max() function, the min() function returns the item in the Python set
with the lowest value.
>>> min(days)
Output
‘Friday’
This is because F has the lowest ASCII value among M, T, W, F, and S.
d. sum()
The sum() functionin Python set returns the arithmetic sum of all the items in
a set.
>>> sum({1,2,3})
Output
6
>>> sum(days)
Output
Traceback (most recent call last):File “<pyshell#72>”, line 1, in <module>
sum(days)
e. any()
This function returns True even if one item in the set has a Boolean value of
True.
>>> any({0})
Output
False
>>> any({0,'0'})
Output
True
It returns True because the string ‘0’ has a Boolean value of True.
f. all()
Unlike the any() function, all() returns True only if all items in the Python set
have a Boolean value of True. Otherwise, it returns False.
>>> all({0,'0'})
Output
False
>>> all(days)
Output
True
g. sorted()
The sorted() function returns a sorted python set to list. It is sorted in
ascending order, but it doesn’t modify the original set.
Output
[1, 2, 3, 3.5, 4, 5, 6]
So far, we have learned about the methods add(), clear(), discard(), pop(),
remove(), and update(). Now, we will see more methods from a more
mathematical point of view.
a. union()
This method performs the union operation on two or more Python sets. What
it does is it returns all the items that are in any of those sets.
Union in Python Set
>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set1.union(set2,set3)
Output
{1, 2, 3, 4, 5, 6, 7}
>>> set1
Output
{1, 2, 3}
As you can see, it did not alter set1. A method does not always alter a set in
Python.
b. intersection()
This method takes as argument sets, and returns the common items in all the
sets.
Intersection Set in Python
>>> set2.intersection(set1)
Output
{3}
>>> set2.intersection(set1,set3)
Output
set()
It returned an empty set because these three sets have nothing in common.
c. difference()
The difference() method returns the difference of two or more sets. It returns
as a set.
Difference Python Set
>>> set1.difference(set2)
Output
{1, 2}
This returns the items that are in set1, but not in set2.
>>> set1.difference(set2,set3)
Output
{1, 2}
d. symmetric_difference()
This method returns all the items that are unique to each set.
Symmetric difference set in Python
>>> set1.symmetric_difference(set2)
Output
{1, 2, 4, 5}
It returned 1 and 2 because they’re in set1, but not in set2. It also returned 4
and 5 because they’re in set2, but not in set1. It did not return 3 because it
exists in both the sets.
e. intersection_update()
As we discussed in intersection(), it does not update the set on which it is
called. For this, we have the intersection_update() method.
>>> set1.intersection_update(set2)
>>> set1
Output
{3}
It stored 3 in set1, because only that was common in set1 and set2.
f. difference_update()
Like intersection-update(), this method updates the Python set with the
difference.
>>> set1={1,2,3}
>>> set2={3,4,5}
>>> set1.difference_update(set2)
>>> set1
Output
{1, 2}
g. symmetric_difference_update()
Like the two methods we discussed before this, it updates the set on which it is
called with the symmetric difference.
>>> set1={1,2,3}
>>> set2={3,4,5}
>>> set1.symmetric_difference_update(set2)
>>> set1
Output
{1, 2, 4, 5}
h. copy()
The copy() method creates a shallow copy of the Python set.
>>> set4=set1.copy()
>>> set1,set4
Output
({1, 2, 4, 5}, {1, 2, 4, 5})
i. isdisjoint()
This method returns True if two sets have a null intersection.
>>> {1,3,2}.isdisjoint({4,5,6})
Output
True
>>> {1,3,2}.isdisjoint({3,4,5},{6,7,8})
Output
Traceback (most recent call last):File “<pyshell#111>”, line 1, in <module>
{1,3,2}.isdisjoint({3,4,5},{6,7,8})
j. issubset()
This method returns true if the set in the argument contains this set.
>>> {1,2}.issubset({1,2,3})
Output
True
>>> {1,2}.issubset({1,2})
Output
True
k. issuperset()
Like the issubset() method, this one returns True if the set contains the set in
the argument.
>>> {1,3,4}.issuperset({1,2})
Output
False
>>> {1,3,4}.issuperset({1})
Output
True
a. Membership
We can apply the ‘in’ and ‘not in’ python operators on items for a set. This tells
us whether they belong to the set.
Output
True
Output
True
Output
12
As you can see, even though we had the order as 1,3,2, it is printed in
ascending order.
9. The frozenset
A frozen set is in-effect an immutable set. You cannot change its values. Also, a
set can’t be used a key for a dictionary, but a frozenset can.
>>> {{1,2}:3}
Output
Traceback (most recent call last):File “<pyshell#123>”, line 1, in <module>
{{1,2}:3}
>>> {frozenset(1,2):3}
Output
Traceback (most recent call last):File “<pyshell#124>”, line 1, in <module>
{frozenset(1,2):3}
As you can see, it takes only one argument. Now let’s see the correct syntax.
>>> {frozenset([1,2]):3}
Output
{frozenset({1, 2}): 3}
1. Value of a Boolean
As we have seen earlier, a Boolean value may either be True or be False. Some
methods like isalpha() or issubset() return a Boolean value.
2. Declaring a Boolean
You can declare a Boolean just like you would declare an integer.
>>> days=True
As you can see here, we didn’t need to delimit the True value by quotes. If you
do that, it is a string, not a Boolean.
Also note that what was once a set, we have reassigned a Boolean to it.
>>> type('True')
Output
<class ‘str’>
>>> bool('Wisdom')
Output
True
>>> bool([])
Output
False
>>> bool(0)
Output
False
>>> bool(0.000000000001)
Output
True
A string has a Boolean value of True, but an empty string has False.
Output
True
>>> bool('')
Output
False
In fact, any empty construct has a Boolean value of False, and a non-empty
one has
Output
True.
>>> bool(())
Output
False
>>> bool((1,3,2))
Output
True
5. Operations on Booleans
a. Arithmetic
You can apply some arithmetic operations to a set. It takes 0 for False, and 1
for True, and then applies the operator to them.
Addition
You can add two or more Booleans. Let’s see how that works.
Output
1
Output
2
>>> False-True
Output
-1
Division
Let’s try dividing Booleans.
>>> False/True
Output
0.0
>>> True/False
Output
Traceback (most recent call last):File “<pyshell#148>”, line 1, in <module>
True/False
This was an exception that raised. We will learn more about exception in a
later lesson.
>>> False%True
>>> True**False
Output
1
>>> False**False
Output
1
>>> 0//1
>>> (True+True)*False+True
Output
1
b. Relational
The relational operators we’ve learnt so far are >, <, >=, <=, !=, and ==. All of
these apply to Boolean values.
We will show you a few examples, you should try the rest of them.
>>> False>True
Output
False
>>> False<=True
Output
True
c. Bitwise
Normally, the bitwise operators operate bit-by bit. For example, the following
code ORs the bits of 2(010) and 5(101), and produces the result 7(111).
>>> 2|5
Output
7
But the bitwise operators also apply to Booleans. Let’s see how.
Bitwise &
It returns True only if both values are True.
>>> True&False
Output
False
>>> True&True
Output
True
Bitwise |
It returns False only if both values are False.
>>> False|True
Output
True
>>> False^True
Output
True
>>> False^False
Output
False
>>> True^True
Output
False
Output
-2
>>> ~False
Output
-1
>>> False>>2
>>> True<<2
Output
4
True is 1. When shifted two places two the left, it results in 100, which is
binary for 4. Hence, it returns 4.
d. Identity
The identity operators ‘is’ and ‘is not’ apply to Booleans.
Output
True
>>> False is 0
Output
False
e. Logical
Finally, even the logical operators apply on Booleans.
This was all about the article on Python set and booleans.
Note: this textbook written by Pranav sirsufale @all rights are reserved
Author: Pranav Sirsufale 👻🔥👀💻