Python Numbers, Type Conversion and Mathematics
Number Data Type in Python
- Python supports integers, floating-point numbers and complex numbers. They are defined as int, float, and complex classes in Python.
- Integers and floating points are separated by the presence or absence of a decimal point.
- For instance, 5 is an integer whereas 5.0 is a floating-point number.
- Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.
- We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class
Let’s look at an example:
a = 5
print(type(a))
print(type(5.0))
c = 5 + 3j
print(c + 3)
print(isinstance(c, complex))
When we run the above program, we get the following output:
<class ‘int’>
<class ‘float’>
(8+3j)
True
While integers can be of any length, a floating-point number is accurate only up to 15 decimal places (the 16th place is inaccurate).
Type Conversion
We can convert one type of number into another. This is also known as coercion.
Operations like addition, subtraction coerce integer to float implicitly (automatically), if one of the operands is float.
>>> 1 + 2.0
3.0
We can see above that 1 (integer) is coerced into 1.0 (float) for addition and the result is also a floating point number.
We can also use built-in functions like int(), float() and complex() to convert between types explicitly. These functions can even convert from strings.
>>> int(2.3)
2
>>> int(-2.8)
-2
>>> float(5)
5.0
>>> complex(‘3+5j’)
(3+5j)
When converting from float to integer, the number gets truncated (decimal parts are removed).
Python Decimal
Python built-in class float performs some calculations that might amaze us. We all know that the sum of 1.1 and 2.2 is 3.3, but Python seems to disagree.
>>> (1.1 + 2.2) == 3.3
False
Python Fractions
Python provides operations involving fractional numbers through its fractions module.
A fraction has a numerator and a denominator, both of which are integers. This module has support for rational number arithmetic.
We can create Fraction objects in various ways. Let’s have a look at them.
import fractions
print(fractions.Fraction(1.5))
print(fractions.Fraction(5))
print(fractions.Fraction(1,3))
Output
3/2
5
1/3
Python Mathematics
Python offers modules like math and random to carry out different mathematics like trigonometry, logarithms, probability and statistics, etc.
import math
print(math.pi)
print(math.cos(math.pi))
print(math.exp(10))
print(math.log10(1000))
print(math.sinh(1))
print(math.factorial(6))
Output
3.141592653589793
-1.0
22026.465794806718
3.0
1.1752011936438014
720
Here is the full list of functions and attributes available in the Python math module.
import random
print(random.randrange(10, 20))
x = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
# Get random choice
print(random.choice(x))
# Shuffle x
random.shuffle(x)
# Print the shuffled x
print(x)
# Print random element
print(random.random())
When we run the above program we get the output as follows.(Values may be different due to the random behavior)
18
e
[‘c’, ‘e’, ‘d’, ‘b’, ‘a’]
0.5682821194654443
Python List
List is one of the most frequently used and very versatile data types used in Python.
How to create a list?
In Python programming, a list is created by placing all the items (elements) inside square brackets [], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed data types
my_list = [1, “Hello”, 3.4]
A list can also have another list as an item. This is called a nested list.
# nested list
my_list = [“mouse”, [8, 4, 6], [‘a’]]
How to access elements from a list?
There are various ways in which we can access the elements of a list.
List Index
# List indexing
my_list = [‘p’, ‘r’, ‘o’, ‘b’, ‘e’]
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
# Negative indexing in lists
my_list = [‘p’,’r’,’o’,’b’,’e’]
print(my_list[-1])
print(my_list[-5])
When we run the above program, we will get the following output:
e
p
List indexing in Python
How to slice lists in Python?
We can access a range of items in a list by using the slicing operator :(colon).
# List slicing in Python
my_list = [‘p’,’r’,’o’,’g’,’r’,’a’,’m’,’i’,’z’]
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
Output
[‘o’, ‘g’, ‘r’]
[‘p’, ‘r’, ‘o’, ‘g’]
[‘a’, ‘m’, ‘i’, ‘z’]
[‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘i’, ‘z’]
Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need two indices that will slice that portion from the list.
How to change or add elements to a list?
Lists are mutable, meaning their elements can be changed unlike string or tuple.
We can use the assignment operator (=) to change an item or a range of items.
# Correcting mistake values in a list
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] = 1
print(odd)
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
print(odd)
Output
[1, 4, 6, 8]
[1, 3, 5, 7]
We can add one item to a list using the append() method or add several items using extend() method.
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)
odd.extend([9, 11, 13])
print(odd)
Output
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]
We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.
# Concatenating and repeating lists
odd = [1, 3, 5]
print(odd + [9, 7, 5])
print([“re”] * 3)
Output
[1, 3, 5, 9, 7, 5]
[‘re’, ‘re’, ‘re’]
Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.
# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)
print(odd)
odd[2:2] = [5, 7]
print(odd)
Output
[1, 3, 9]
[1, 3, 5, 7, 9]
Python List Methods
Methods that are available with list objects in Python programming are tabulated below.
They are accessed as list.method(). Some of the methods have already been used above.
Some examples of Python list methods:
# Python list methods
my_list = [3, 8, 1, 6, 0, 8, 4]
# Output: 1
print(my_list.index(8))
# Output: 2
print(my_list.count(8))
my_list.sort()
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse()
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
Output
1
2
[0, 1, 3, 4, 6, 8, 8]
[8, 8, 6, 4, 3, 1, 0]
List Comprehension: Elegant way to create new List
List comprehension is an elegant and concise way to create a new list from an existing list in Python.
A list comprehension consists of an expression followed by for statement inside square brackets.
Here is an example to make a list with each item being increasing power of 2.
pow2 = [2 ** x for x in range(10)]
print(pow2)
Output
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
This code is equivalent to:
pow2 = []
for x in range(10):
pow2.append(2 ** x)
True
False
True
Iterating Through a List
Using a for loop we can iterate through each item in a list.
for fruit in [‘apple’,’banana’,’mango’]:
print(“I like”,fruit)
Output
I like apple
I like banana
I like mango
Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas.
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, “Hello”, 3.4)
print(my_tuple)
# nested tuple
my_tuple = (“mouse”, [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output
()
(1, 2, 3)
(1, ‘Hello’, 3.4)
(‘mouse’, [8, 4, 6], (1, 2, 3))
A tuple can also be created without using parentheses. This is known as tuple packing.
my_tuple = 3, 4.6, “dog”
print(my_tuple)
# tuple unpacking is also possible
a, b, c = my_tuple
print(a) # 3
print(b) # 4.6
print(c) # dog
Output
(3, 4.6, ‘dog’)
3
4.6
dog
Creating a tuple with one element is a bit tricky.
Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.
my_tuple = (“hello”)
print(type(my_tuple)) # <class ‘str’>
# Creating a tuple having one element
my_tuple = (“hello”,)
print(type(my_tuple)) # <class ‘tuple’>
# Parentheses is optional
my_tuple = “hello”,
print(type(my_tuple)) # <class ‘tuple’>
Output
<class ‘str’>
<class ‘tuple’>
<class ‘tuple’>
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.
# Deleting tuples
my_tuple = (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘i’, ‘z’)
# can’t delete items
# TypeError: ‘tuple’ object doesn’t support item deletion
# del my_tuple[3]
# Can delete an entire tuple
del my_tuple
# NameError: name ‘my_tuple’ is not defined
print(my_tuple)
Output
Traceback (most recent call last):
File “<string>”, line 12, in <module>
NameError: name ‘my_tuple’ is not defined
Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two methods are available.
Some examples of Python tuple methods:
my_tuple = (‘a’, ‘p’, ‘p’, ‘l’, ‘e’,)
print(my_tuple.count(‘p’)) # Output: 2
print(my_tuple.index(‘l’)) # Output: 3
Output
2
3
Python Strings
What is String in Python?
A string is a sequence of characters.
How to create a string in Python?
Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.
# defining strings in Python
# all of the following are equivalent
my_string = ‘Hello’
print(my_string)
my_string = “Hello”
print(my_string)
my_string = ”’Hello”’
print(my_string)
# triple quotes string can extend multiple lines
my_string = “””Hello, welcome to
the world of Python”””
print(my_string)
When you run the program, the output will be:
Hello
Hello
Hello
Hello, welcome to
the world of Python
How to access characters in a string?
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator :(colon).
#Accessing string characters in Python
str = ‘programiz’
print(‘str = ‘, str)
#first character
print(‘str[0] = ‘, str[0])
#last character
print(‘str[-1] = ‘, str[-1])
#slicing 2nd to 5th character
print(‘str[1:5] = ‘, str[1:5])
#slicing 6th to 2nd last character
print(‘str[5:-2] = ‘, str[5:-2])
When we run the above program, we get the following output:
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
If we try to access an index out of the range or use numbers other than an integer, we will get errors.
# index must be in range
>>> my_string[15]
…
IndexError: string index out of range
# index must be an integer
>>> my_string[1.5]
…
TypeError: string indices must be integers
Slicing can be best visualized by considering the index to be between the elements as shown below.
If we want to access a range, we need the index that will slice the portion from the string.
String Slicing in Python
How to change or delete a string?
Strings are immutable. This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name.
>>> my_string = ‘programiz’
>>> my_string[5] = ‘a’
…
TypeError: ‘str’ object does not support item assignment
>>> my_string = ‘Python’
>>> my_string
‘Python’
We cannot delete or remove characters from a string. But deleting the string entirely is possible using the del keyword.
>>> del my_string[1]
…
TypeError: ‘str’ object doesn’t support item deletion
>>> del my_string
>>> my_string
…
NameError: name ‘my_string’ is not defined
Python String Operations
There are many operations that can be performed with strings which makes it one of the most used data types in Python.
Concatenation of Two or More Strings
Joining of two or more strings into a single one is called concatenation.
The + operator does this in Python. Simply writing two string literals together also concatenates them.
The * operator can be used to repeat the string for a given number of times.
# Python String Operations
str1 = ‘Hello’
str2 =’World!’
# using +
print(‘str1 + str2 = ‘, str1 + str2)
# using *
print(‘str1 * 3 =’, str1 * 3)
When we run the above program, we get the following output:
str1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello
Writing two string literals together also concatenates them like + operator.
If we want to concatenate strings in different lines, we can use parentheses.
>>> # two string literals together
>>> ‘Hello ”World!’
‘Hello World!’
>>> # using parentheses
>>> s = (‘Hello ‘
… ‘World’)
>>> s
‘Hello World’
Iterating Through a string
We can iterate through a string using a for loop. Here is an example to count the number of ‘l’s in a string.
# Iterating through a string
count = 0
for letter in ‘Hello World’:
if(letter == ‘l’):
count += 1
print(count,’letters found’)
When we run the above program, we get the following output:
3 letters found
String Membership Test
We can test if a substring exists within a string or not, using the keyword in.
>>> ‘a’ in ‘program’
True
>>> ‘at’ not in ‘battle’
False
Built-in functions to Work with Python
Various built-in functions that work with sequence work with strings as well.
Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration.
Similarly, len() returns the length (number of characters) of the string.
str = ‘cold’
# enumerate()
list_enumerate = list(enumerate(str))
print(‘list(enumerate(str) = ‘, list_enumerate)
#character count
print(‘len(str) = ‘, len(str))
When we run the above program, we get the following output:
list(enumerate(str) = [(0, ‘c’), (1, ‘o’), (2, ‘l’), (3, ‘d’)]
len(str) = 4
Python String Formatting
Escape Sequence
If we want to print a text like He said, “What’s there?”, we can neither use single quotes nor double quotes. This will result in a SyntaxError as the text itself contains both single and double quotes.
>>> print(“He said, “What’s there?””)
…
SyntaxError: invalid syntax
>>> print(‘He said, “What’s there?”‘)
…
SyntaxError: invalid syntax
One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.
An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.
# using triple quotes
print(”’He said, “What’s there?””’)
# escaping single quotes
print(‘He said, “What\’s there?”‘)
# escaping double quotes
print(“He said, \”What’s there?\””)
When we run the above program, we get the following output:
He said, “What’s there?”
He said, “What’s there?”
He said, “What’s there?”
Here is a list of all the escape sequences supported by Python.
Escape Sequence | Description |
\newline | Backslash and newline ignored |
\\ | Backslash |
\’ | Single quote |
\” | Double quote |
\a | ASCII Bell |
\b | ASCII Backspace |
\f | ASCII Formfeed |
\n | ASCII Linefeed |
\r | ASCII Carriage Return |
\t | ASCII Horizontal Tab |
\v | ASCII Vertical Tab |
\ooo | Character with octal value ooo |
\xHH | Character with hexadecimal value HH |
Here are some examples
>>> print(“C:\\Python32\\Lib”)
C:\Python32\Lib
>>> print(“This is printed\nin two lines”)
This is printed
in two lines
>>> print(“This is \x48\x45\x58 representation”)
This is HEX representation
Raw String to ignore escape sequence
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.
>>> print(“This is \x61 \ngood example”)
This is a
good example
>>> print(r”This is \x61 \ngood example”)
This is \x61 \ngood example
The format() Method for Formatting Strings
The format() method that is available with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces {} as placeholders or replacement fields which get replaced.
We can use positional arguments or keyword arguments to specify the order.
# Python string format() method
# default(implicit) order
default_order = “{}, {} and {}”.format(‘John’,’Bill’,’Sean’)
print(‘\n— Default Order —‘)
print(default_order)
# order using positional argument
positional_order = “{1}, {0} and {2}”.format(‘John’,’Bill’,’Sean’)
print(‘\n— Positional Order —‘)
print(positional_order)
# order using keyword argument
keyword_order = “{s}, {b} and {j}”.format(j=’John’,b=’Bill’,s=’Sean’)
print(‘\n— Keyword Order —‘)
print(keyword_order)
When we run the above program, we get the following output:
— Default Order —
John, Bill and Sean
— Positional Order —
Bill, John and Sean
— Keyword Order —
Sean, Bill and John
The format() method can have optional format specifications. They are separated from the field name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space.
We can also format integers as binary, hexadecimal, etc. and floats can be rounded or displayed in the exponent format. There are tons of formatting you can use. Visit here for all the string formatting available with the format() method.
>>> # formatting integers
>>> “Binary representation of {0} is {0:b}”.format(12)
‘Binary representation of 12 is 1100’
>>> # formatting floats
>>> “Exponent representation: {0:e}”.format(1566.345)
‘Exponent representation: 1.566345e+03’
>>> # round off
>>> “One third is: {0:.3f}”.format(1/3)
‘One third is: 0.333’
>>> # string alignment
>>> “|{:<10}|{:^10}|{:>10}|”.format(‘butter’,’bread’,’ham’)
‘|butter | bread | ham|’
Old style formatting
We can even format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.
>>> x = 12.3456789
>>> print(‘The value of x is %3.2f’ %x)
The value of x is 12.35
>>> print(‘The value of x is %3.4f’ %x)
The value of x is 12.3457
Common Python String Methods
There are numerous methods available with the string object. The format() method that we mentioned above is one of them. Some of the commonly used methods are lower(), upper(), join(), split(), find(), replace() etc. Here is a complete list of all the built-in methods to work with strings in Python.
>>> “PrOgRaMiZ”.lower()
‘programiz’
>>> “PrOgRaMiZ”.upper()
‘PROGRAMIZ’
>>> “This will split all words into a list”.split()
[‘This’, ‘will’, ‘split’, ‘all’, ‘words’, ‘into’, ‘a’, ‘list’]
>>> ‘ ‘.join([‘This’, ‘will’, ‘join’, ‘all’, ‘words’, ‘into’, ‘a’, ‘string’])
‘This will join all words into a string’
>>> ‘Happy New Year’.find(‘ew’)
7
>>> ‘Happy New Year’.replace(‘Happy’,’Brilliant’)
‘Brilliant New Year’
Python Sets
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.
Creating Python Sets
A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function.
It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, “Hello”, (1, 2, 3)}
print(my_set)
Output
{1, 2, 3}
{1.0, (1, 2, 3), ‘Hello’}
Try the following examples as well.
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)
# set cannot have mutable items
# here [3, 4] is a mutable list
# this will cause an error.
my_set = {1, 2, [3, 4]}
Output
{1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
File “<string>”, line 15, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: ‘list’
Creating an empty set is a bit tricky.
Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements, we use the set() function without any argument.
# Distinguish set and dictionary while creating empty set
# initialize a with {}
a = {}
# check data type of a
print(type(a))
# initialize a with set()
a = set()
# check data type of a
print(type(a))
Output
<class ‘dict’>
<class ‘set’>
Modifying a set in Python
Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Set data type does not support it.
We can add a single element using the add() method, and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.
# initialize my_set
my_set = {1, 3}
print(my_set)
# if you uncomment line 9,
# you will get an error
# TypeError: ‘set’ object does not support indexing
# my_set[0]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)
Output
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
Removing elements from a set
A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if the element is not present in the set. On the other hand, the remove() function will raise an error in such a condition (if element is not present in the set).
The following example will illustrate this.
# Difference between discard() and remove()
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)
Output
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File “<string>”, line 28, in <module>
KeyError: 2
Similarly, we can remove and return an item using the pop() method.
Since set is an unordered data type, there is no way of determining which item will be popped. It is completely arbitrary.
We can also remove all the items from a set using the clear() method.
# initialize my_set
# Output: set of unique elements
my_set = set(“HelloWorld”)
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
my_set.pop()
print(my_set)
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
print(my_set)
Output
{‘H’, ‘l’, ‘r’, ‘W’, ‘o’, ‘d’, ‘e’}
H
{‘r’, ‘W’, ‘o’, ‘d’, ‘e’}
set()
Python Set Operations
Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Set Union
Set Union in Python
Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the union() method.
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Output
{1, 2, 3, 4, 5, 6, 7, 8}
Try the following examples on Python shell.
# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
# use union function on B
>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection
Set Intersection in Python
Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the intersection() method.
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)
Output
{4, 5}
Try the following examples on Python shell.
# use intersection function on A
>>> A.intersection(B)
{4, 5}
# use intersection function on B
>>> B.intersection(A)
{4, 5}
Set Difference
Set Difference in Python
Difference of the set B from set A(A – B) is a set of elements that are only in A but not in B. Similarly, B – A is a set of elements in B but not in A.
Difference is performed using – operator. Same can be accomplished using the difference() method.
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use – operator on A
# Output: {1, 2, 3}
print(A – B)
Output
{1, 2, 3}
Try the following examples on Python shell.
# use difference function on A
>>> A.difference(B)
{1, 2, 3}
# use – operator on B
>>> B – A
{8, 6, 7}
# use difference function on B
>>> B.difference(A)
{8, 6, 7}
Set Symmetric Difference
Set Symmetric Difference in Python
Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the intersection).
Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference().
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Output
{1, 2, 3, 6, 7, 8}
Try the following examples on Python shell.
# use symmetric_difference function on A
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
# use symmetric_difference function on B
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
Other Python Set Methods
There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with the set objects:
Method | Description |
add() | Adds an element to the set |
clear() | Removes all elements from the set |
copy() | Returns a copy of the set |
difference() | Returns the difference of two or more sets as a new set |
difference_update() | Removes all elements of another set from this set |
discard() | Removes an element from the set if it is a member. (Do nothing if the element is not in set) |
intersection() | Returns the intersection of two sets as a new set |
intersection_update() | Updates the set with the intersection of itself and another |
isdisjoint() | Returns True if two sets have a null intersection |
issubset() | Returns True if another set contains this set |
issuperset() | Returns True if this set contains another set |
pop() | Removes and returns an arbitrary set element. Raises KeyError if the set is empty |
remove() | Removes an element from the set. If the element is not a member, raises a KeyError |
symmetric_difference() | Returns the symmetric difference of two sets as a new set |
symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |
union() | Returns the union of sets in a new set |
update() | Updates the set with the union of itself and others |
Other Set Operations
Set Membership Test
We can test if an item exists in a set or not, using the in keyword.
# in keyword in a set
# initialize my_set
my_set = set(“apple”)
# check if ‘a’ is present
# Output: True
print(‘a’ in my_set)
# check if ‘p’ is present
# Output: False
print(‘p’ not in my_set)
Output
True
False
Iterating Through a Set
We can iterate through each item in a set using a for loop.
>>> for letter in set(“apple”):
… print(letter)
…
a
p
e
l
Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with sets to perform different tasks.
Function | Description |
all() | Returns True if all elements of the set are true (or if the set is empty). |
any() | Returns True if any element of the set is true. If the set is empty, returns False. |
enumerate() | Returns an enumerate object. It contains the index and value for all the items of the set as a pair. |
len() | Returns the length (the number of items) in the set. |
max() | Returns the largest item in the set. |
min() | Returns the smallest item in the set. |
sorted() | Returns a new sorted list from elements in the set(does not sort the set itself). |
sum() | Returns the sum of all elements in the set. |
Python Dictionary
Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.
An item has a key and a corresponding value that is expressed as a pair (key: value).
While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: ‘apple’, 2: ‘ball’}
# dictionary with mixed keys
my_dict = {‘name’: ‘John’, 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:’apple’, 2:’ball’})
# from sequence having each item as a pair
my_dict = dict([(1,’apple’), (2,’ball’)])
As you can see from above, we can also create a dictionary using the built-in dict() function.
Accessing Elements from Dictionary
While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside square brackets [] or with the get() method.
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.
# get vs [] for retrieving elements
my_dict = {‘name’: ‘Jack’, ‘age’: 26}
# Output: Jack
print(my_dict[‘name’])
# Output: 26
print(my_dict.get(‘age’))
# Trying to access keys which doesn’t exist throws error
# Output None
print(my_dict.get(‘address’))
# KeyError
print(my_dict[‘address’])
Output
Jack
26
None
Traceback (most recent call last):
File “<string>”, line 15, in <module>
print(my_dict[‘address’])
KeyError: ‘address’
Changing and Adding Dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to the dictionary.
# Changing and adding Dictionary Elements
my_dict = {‘name’: ‘Jack’, ‘age’: 26}
# update value
my_dict[‘age’] = 27
#Output: {‘age’: 27, ‘name’: ‘Jack’}
print(my_dict)
# add item
my_dict[‘address’] = ‘Downtown’
# Output: {‘address’: ‘Downtown’, ‘age’: 27, ‘name’: ‘Jack’}
print(my_dict)
Output
{‘name’: ‘Jack’, ‘age’: 27}
{‘name’: ‘Jack’, ‘age’: 27, ‘address’: ‘Downtown’}
Removing elements from Dictionary
We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# Removing elements from a dictionary
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error
print(squares)
Output
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Traceback (most recent call last):
File “<string>”, line 30, in <module>
print(squares)
NameError: name ‘squares’ is not defined
Python Dictionary Methods
Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.
Method | Description |
clear() | Removes all items from the dictionary. |
copy() | Returns a shallow copy of the dictionary. |
fromkeys(seq[, v]) | Returns a new dictionary with keys from seq and value equal to v (defaults to None). |
get(key[,d]) | Returns the value of the key. If the key does not exist, returns d (defaults to None). |
items() | Return a new object of the dictionary’s items in (key, value) format. |
keys() | Returns a new object of the dictionary’s keys. |
pop(key[,d]) | Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError. |
popitem() | Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. |
setdefault(key[,d]) | Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None). |
update([other]) | Updates the dictionary with the key/value pairs from other, overwriting existing keys. |
values() | Returns a new object of the dictionary’s values |
Here are a few example use cases of these methods.
# Dictionary Methods
marks = {}.fromkeys([‘Math’, ‘English’, ‘Science’], 0)
# Output: {‘English’: 0, ‘Math’: 0, ‘Science’: 0}
print(marks)
for item in marks.items():
print(item)
# Output: [‘English’, ‘Math’, ‘Science’]
print(list(sorted(marks.keys())))
Output
{‘Math’: 0, ‘English’: 0, ‘Science’: 0}
(‘Math’, 0)
(‘English’, 0)
(‘Science’, 0)
[‘English’, ‘Math’, ‘Science’]
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
A dictionary comprehension can optionally contain more for or if statements.
An optional if statement can filter out items to form the new dictionary.
Here are some examples to make a dictionary with only odd items.
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}
print(odd_squares)
Output
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
Other Dictionary Operations
Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for the keys and not for the values.
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
# membership tests for key only not value
# Output: False
print(49 in squares)
Output
True
True
False
Iterating Through a Dictionary
We can iterate through each key in a dictionary using a for loop.
# Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
Output
1
9
25
49
81
Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks.
Function | Description |
all() | Return True if all keys of the dictionary are True (or if the dictionary is empty). |
any() | Return True if any key of the dictionary is true. If the dictionary is empty, return False. |
len() | Return the length (the number of items) in the dictionary. |
cmp() | Compares items of two dictionaries. (Not available in Python 3) |
sorted() | Return a new sorted list of keys in the dictionary. |
Here are some examples that use built-in functions to work with a dictionary.
# Dictionary Built-in Functions
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: False
print(all(squares))
# Output: True
print(any(squares))
# Output: 6
print(len(squares))
# Output: [0, 1, 3, 5, 7, 9]
print(sorted(squares))
Output
False
True
6
[0, 1, 3, 5, 7, 9]