Python Material
TOPIC – 3 PYTHON DATA TYPES
Python data types offers, enabling you to manipulate and manage data with precision and
flexibility. Additionally, we'll delve into the dynamic world of data conversion with casting, and
then move on to explore the versatile collections Python provides, including lists, tuples, sets,
dictionaries, and arrays.
By the end of this section, you'll not only grasp the essence of Python's data types but also wield
them proficiently to tackle a wide array of programming challenges with confidence.
a. Strings
b. Numbers
c. Booleans
d. Python List
e. Python Tuples
f. Python Sets
g. Python Dictionary
h. Python Arrays
i. Type Casting
TOPIC 3 (a)Python String
A String is a data structure in Python Programming that represents a sequence of characters. It is
an immutable data type, meaning that once you have created a string, you cannot change it.
Python String are used widely in many different applications, such as storing and manipulating
text data, representing names, addresses, and other types of data that can be represented as
text.
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Table of Content
i. What is a String in Python?
ii. Create a String in Python
iii. Accessing characters in Python String
iv. String Slicing Python
v. Python String Reversed
vi. Deleting/Updating from a String
vii. Escape Sequencing in Python
viii. Python String Formatting
ix. Useful Python String Operations
x. Python String constants
xi. Deprecated string functions
What is a String in Python?
Python Programming does not have a character data type, a single character is simply a string
with a length of 1. To explore more about Python String go through a free online Python course.
Now, let’s see the Python string syntax:
Syntax of String Data Type in Python
string_variable = 'Hello, world!'
Example of string data type in Python
Pythonstring_0 = "A Computer Science portal for decent"
print(string_0)
print(type(string_0))
Output:
A Computer Science portal for decent
<class 'str'>
Create a String in Python
Strings in Python can be created using single quotes or double quotes or even triple quotes. Let
us see how we can define a string in Python or how to write string in Python.
2 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Example:
In this example, we will demonstrate different ways to create a Python String. We will create a
string using single quotes (‘ ‘), double quotes (” “), and triple double quotes (“”” “””). The triple
quotes can be used to declare multiline strings in Python.
# Creating a String
# with single Quotes
String1 = 'Welcome to the Decent World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a ABC"
print("\nString with the use of Double Quotes: ")
print(String1)
# Creating a String
# with triple Quotes
String1 = '''I'm a ABC and I live in a world of "Decent"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Knowledge
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
3 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
String with the use of Single Quotes:
Welcome to the Decent World
String with the use of Double Quotes:
I'm a ABC
String with the use of Triple Quotes:
I'm a ABC and I live in a world of "Decent"
Creating a multiline String:
Knowledge
For
Life
Accessing characters in Python String
In Python Programming tutorials, individual characters of a String can be accessed by using the
method of Indexing. Indexing allows negative address references to access characters from the
back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so
on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to
be passed as an index, float or other types that will cause a TypeError.
Python String syntax indexing
Python String Positive Indexing
In this example, we will define a string in Python Programming and access its characters using
positive indexing. The 0th element will be the first character of the string.
String1 = "DecentforPython"
print("Initial String: ", String1)
# Printing First character
print("First character of String is: ", String1[0])
Output:
Initial String: DecentforPython
First character of String is: D
4 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Python String Negative Indexing
In this example, we will access its characters using negative indexing. The -3th element is the
third last character of the string.
String1 = "DecentforPython"
print("Initial String: ", String1)
# Printing Last character
print("Last character of String is: ", String1[-3])
Output
Initial String: DecentforPython
Last character of String is: h
String Slicing Python
In Python Programming tutorials, the String Slicing method is used to access a range of
characters in the String. Slicing in a String is done by using a Slicing operator, i.e., a colon (:). One
thing to keep in mind while using this method is that the string returned after slicing includes the
character at the start index but not the character at the last index.
In this example, we will use the string-slicing method to extract a substring of the original string.
The [3:12] indicates that the string slicing will start from the 3rd index of the string to the 12th
index, (12th character not including). We can also use negative indexing in string slicing.
# Creating a String
String1 = "DecentforPython"
print("Initial String: ")
print(String1)
# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
# Printing characters between
# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
5 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
Initial String:
DecentforPython
Slicing characters from 3-12:
entforPyt
Slicing characters between 3rd and 2nd last character:
entforPyth
Python String Reversed :
In Python Programming tutorials, By accessing characters from a string, we can also reverse
strings in Python Programming. We can Reverse a string by using String slicing method.
In this example, we will reverse a string by accessing the index. We did not specify the first two
parts of the slice indicating that we are considering the whole string, from the start index to the
last index.
#Program to reverse a string
kbc= "kaunbanegakarorepati"
print(kbc[::-1])
Output:
itaperorakagenabnuak
BuildIn Reverse Function in Python
We can also reverse a string by using built-in join and reversed functions, and passing the string
as the parameter to the reversed() function.
# Program to reverse a string
kbc= "kaunbanegakarorepati"
# Reverse the string using reversed and join function
kbc = "".join(reversed(kbc))
print(kbc)
Output:
itaperorakagenabnuak
Deleting/Updating from a String
In Python, the Updation or deletion of characters from a String is not allowed. This will cause an
error because item assignment or item deletion from a String is not supported. Although deletion
6 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
of the entire String is possible with the use of a built-in del keyword. This is because Strings are
immutable, hence elements of a String cannot be changed once assigned. Only new strings can
be reassigned to the same name.
Updating a character
A character of a string can be updated in Python by first converting the string into a Python
List and then updating the element in the list. As lists are mutable in nature, we can update the
character and then convert the list back into the String.
Another method is using the string slicing method. Slice the string before the character you want
to update, then add the new character and finally add the other part of the string again by string
slicing.
Example:
In this example, we are using both the list and the string slicing method to update a character.
We converted the String1 to a list, changes its value at a particular element, and then converted
it back to a string using the Python string join() method.
In the string-slicing method, we sliced the string up to the character we want to update,
concatenated the new character, and finally concatenate the remaining part of the string.
# Python Program to Update
# character of a String
String1 = "Hello, I'm a Big B"
print("Initial String: ")
print(String1)
# Updating a character of the String
## As python strings are immutable, they don't support item updation directly
### there are following two ways
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)
#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
7 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
Initial String:
Hello, I'm a Big B
Updating character at 2nd Index:
Heplo, I'm a Big B
Heplo, I'm a Big B
Updating Entire String
In Python Programming, As Python strings are immutable in nature, we cannot update the
existing string. We can only assign a completely new value to the variable with the same name.
Example: In this example, we first assign a value to ‘String1’ and then updated it by assigning a
completely different value to it. We simply changed its reference.
# Python Program to Update
# entire String
String1 = "Hello, I'm a Big B"
print("Initial String: ")
print(String1)
# Updating a String
String1 = "Welcome to the KBC"
print("\nUpdated String: ")
print(String1)
Output:
Initial String:
Hello, I'm a Big B
Updated String:
Welcome to the KBC
Deleting a character
Python strings are immutable, that means we cannot delete a character from it. When we try to
delete thecharacter using the del keyword, it will generate an error.
8 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# Python Program to delete
# character of a String
String1 = "Hello, I'm a Big B"
print("Initial String: ")
print(String1)
print("Deleting character at 2nd Index: ")
del String1[2]
print(String1)
Output:
Initial String:
Hello, I'm a Big B
Deleting character at 2nd Index:
Traceback (most recent call last):
File "D:/DECENT COMPUTER EDUCATION/Python 15 weeks course/delete [Link]", line 8, in
<module>
del String1[2]
TypeError: 'str' object doesn't support item deletion
But using slicing we can remove the character from the original string and store the result in a
new string.
Example: In this example, we will first slice the string up to the character that we want to delete
and then concatenate the remaining string next from the deleted character.
# Python Program to Delete
# characters from a String
String1 = "Hello, I'm a Big B"
print("Initial String: ")
print(String1)
9 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)
Output:
Initial String:
Hello, I'm a Big B
Deleting character at 2nd Index:
Helo, I'm a Big B
Deleting Entire String
In Python Programming, Deletion of the entire string is possible with the use of del keyword.
Further, if we try to print the string, this will produce an error because the String is deleted and is
unavailable to be printed.
# Python Program to Delete
# entire String
String1 = "Hello, I'm a Big B"
print("Initial String: ")
print(String1)
# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Output :
Initial String:
Hello, I'm a Big B
10 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Deleting entire String:
Traceback (most recent call last):
File "D:/DECENT COMPUTER EDUCATION/Python 15 weeks course/delete etire [Link]", line
10, in <module>
print(String1)
NameError: name 'String1' is not defined
Escape Sequencing in Python
While printing Strings with single and double quotes in it causes SyntaxError because String
already contains Single and Double Quotes and hence cannot be printed with the use of either of
these. Hence, to print such a String either Triple Quotes are used or Escape sequences are used
to print Strings.
Escape sequences start with a backslash and can be interpreted differently. If single quotes are
used to represent a string, then all the single quotes present in the string must be escaped and
the same is done for Double Quotes.
# Initial String
String1 = '''I'm a "Don"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
# Escaping Single Quote
String1 = 'I\'m a "Don"'
print("\nEscaping Single Quote: ")
print(String1)
# Escaping Double Quotes
String1 = "I'm a \"Don\""
print("\nEscaping Double Quotes: ")
print(String1)
11 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# Printing Paths with the
# use of Escape Sequences
String1 = "C:\\Python\\Decent\\"
print("\nEscaping Backslashes: ")
print(String1)
# Printing Paths with the
# use of Tab
String1 = "Hi\tDon"
print("\nTab: ")
print(String1)
# Printing Paths with the
# use of New Line
String1 = "Python\nDon"
print("\nNew Line: ")
print(String1)
Output:
Initial String with use of Triple Quotes:
I'm a "Don"
Escaping Single Quote:
I'm a "Don"
Escaping Double Quotes:
I'm a "Don"
Escaping Backslashes:
C:\Python\Decent\
12 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Tab:
Hi Don
New Line:
Python
Don
Python String Formatting
Strings in Python or string data type in Python can be formatted with the use of format() method
which is a very versatile and powerful tool for formatting Strings. Format method in String
contains curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.
Example 1: In this example, we will declare a string which contains the curly braces {} that acts
as a placeholders and provide them values to see how string declaration position matters.
# Python Program for
# Formatting of Strings
# Default order
String1 = "{} {} {}".format('Decent', 'For', 'Python')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Decent', 'For', 'Python')
print("\nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{d} {f} {p}".format(d='Decent', f='For', p='Python')
print("\nPrint String in order of Keywords: ")
print(String1)
13 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
Print String in default order:
Decent For Python
Print String in Positional order:
For Decent Python
Print String in order of Keywords:
Decent For Python
TOPIC : 3 (b) Python Numbers
In Python, “Numbers” is a category that encompasses different types of numeric
data. Python supports various types of numbers, including integers, floating-point numbers, and
complex numbers. Here’s a brief overview of each:
Table of Content
• Python Integer
• Python Float
• Python Complex
• Type Conversion in Python
• Decimal Numbers in Python
Python Integer
Python int is the whole number, including negative numbers but not fractions. In Python, there is
no limit to how long an integer value can be.
Example 1: Creating int and checking type
num = -8
# print the data type
print(type(num))
Output:
<class 'int'>
14 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Example 2: Performing arithmetic Operations on int type
a=5
b=6
# Addition
c=a+b
print("Addition:",c)
d=9
e=6
# Subtraction
f=d-e
print("Subtraction:",f)
g=8
h=2
# Division
i = g // h
print("Division:",i)
j=3
k=5
# Multiplication
l=j*k
print("Multiplication:",l)
m = 25
n=5
# Modulus
o=m%n
print("Modulus:",o)
p=6
q=2
15 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# Exponent
r = p ** q
print("Exponent:",r)
Output:
Addition: 11
Subtraction: 3
Division: 4
Multiplication: 15
Modulus: 0
Exponent: 36
Python Float
This is a real number with a floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer may be appended to
specify scientific notation. . Some examples of numbers that are represented as floats are 0.5 and
-7.823457.
They can be created directly by entering a number with a decimal point, or by using operations
such as division on integers. Extra zeros present at the number’s end are ignored automatically.
Example 1: Creating float and checking type
num = 3/4
# print the data type
print(type(num))
Output:
<class 'float'>
As we have seen, dividing any two integers produces a float. A float is also produced by running
an operation on two floats, or a float and an integer.
num = 6 * 7.0
print(type(num))
16 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
<class 'float'>
Example 2: Performing arithmetic Operations on the float type
a = 5.5
b = 3.2
# Addition
c=a+b
print("Addition:", c)
# Subtraction
c = a-b
print("Subtraction:", c)
# Division
c = a/b
print("Division:", c)
# Multiplication
c = a*b
print("Multiplication:", c)
Output
Addition: 8.7
Subtraction: 2.3
Division: 1.71875
Multiplication: 17.6
Note: The accuracy of a floating-point number is only up to 15 decimal places, the 16th place can
be inaccurate.
17 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Python Complex
A complex number is a number that consists of real and imaginary parts. For example, 2 + 3j is a
complex number where 2 is the real component, and 3 multiplied by j is an imaginary part.
Example 1: Creating Complex and checking type
num = 6 + 9j
print(type(num))
Output:
<class 'complex'>
Example 2: Performing arithmetic operations on complex type
a = 1 + 5j
b = 2 + 3j
# Addition
c=a+b
print("Addition:",c)
d = 1 + 5j
e = 2 - 3j
# Subtraction
f=d-e
print("Subtraction:",f)
g = 1 + 5j
h = 2 + 3j
# Division
i=g/h
print("Division:",i)
j = 1 + 5j
k = 2 + 3j
# Multiplication
l=j*k
print("Multiplication:",l)
18 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
Addition: (3+8j)
Subtraction: (-1+8j)
Division: (1.307692307692308+0.5384615384615384j)
Multiplication: (-13+13j)
Type Conversion in Python
We can convert one number into the other form by two methods:
Using Arithmetic Operations:
We can use operations like addition, and subtraction to change the type of number
implicitly(automatically), if one of the operands is float. This method is not working for complex
numbers.
Example: Type conversion using arithmetic operations
a = 1.6
b=5
c=a+b
print(c)
Output:
6.6
Using built-in functions
We can also use built-in functions like int(), float() and complex() to convert into different types
explicitly.
Example: Type conversion using built-in functions
a=2
print(float(a))
b = 5.6
print(int(b))
19 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
c = '3'
print(type(int(c)))
d = '5.6'
print(type(float(c)))
e=5
print(complex(e))
f = 6.5
print(complex(f))
Output:
2.0
<class 'int'>
<class 'float'>
(5+0j)
(6.5+0j)
When we convert float to int, the decimal part is truncated.
Note:
1. We can’t convert a complex data type number into int data type and float data type
numbers.
2. We can’t apply complex built-in functions on strings.
Decimal Numbers in Python
Arithmetic operations on the floating number can give some unexpected results.
Example 1: Let’s consider a case where we want to add 1.1 to 2.2. You all must be wondering
why the result of this operation should be 3.3 but let’s see the output given by Python.
a = 1.1
b = 2.2
c = a+b
print(c)
20 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
3.3000000000000003
Example 2: You can the result is unexpected. Let’s consider another case where we will subtract
1.2 and 1.0. Again we will expect the result as 0.2, but let’s see the output given by Python.
a = 1.2
b = 1.0
c = a-b
print(c)
Output:
0.19999999999999996
You all must be thinking that something is wrong with Python, but it is not. This has little to do
with Python, and much more to do with how the underlying platform handles floating-point
numbers. It’s a normal case encountered when handling floating-point numbers internally in a
system. It’s a problem caused when the internal representation of floating-point numbers, which
uses a fixed number of binary digits to represent a decimal number. It is difficult to represent
some decimal numbers in binary, so in many cases, it leads to small roundoff errors.
In this case, taking 1.2 as an example, the representation of 0.2 in binary is
0.00110011001100110011001100…… and so on. It is difficult to store this infinite decimal
number internally. Normally a float object’s value is stored in binary floating-point with a fixed
precision (typically 53 bits). So we represent 1.2 internally as,
1.0011001100110011001100110011001100110011001100110011
Which is exactly equal to :
1.1999999999999999555910790149937383830547332763671875
For such cases, Python’s decimal module comes to the rescue. As stated earlier the floating-
point number precision is only up to 15 places but in the decimal number, the precision is user-
defined. It performs the operations on the floating-point numbers in the same manner as we
learned in school.
Let’s see the above two examples and try to solve them using the decimal number.
21 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
TOExample:
import decimal
a = [Link]('1.1')
b = [Link]('2.2')
c = a+b
print(c)
Output
3.3
We can use a decimal module for the cases –
• When we want to define the required accuracy on our own
• For financial applications that need precise decimal representations
TOPIC: 3 (c) Python Boolean
Python boolean type is one of the built-in data types provided by Python, which represents one
of the two values i.e. True or False. Generally, it is used to represent the truth values of the
Python Boolean Type
The boolean value can be of two types only i.e. either True or False. The output <class
‘bool’> indicates the variable is a boolean data type.
a = True
print(type(a))
b = False
print(type(b))
Output:
<class 'bool'>
<class 'bool'>
22 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Evaluate Variables and Expressions
We can evaluate values and variables using the Python bool() function. This method is used to
return or convert a value to a Boolean value i.e., True or False, using the standard truth testing
procedure.
Syntax: bool([x])
Python bool() Function
We can also evaluate expressions without using the bool() function also. The Boolean values will
be returned as a result of some sort of comparison. In the example below the variable res will
store the boolean value of False after the equality comparison takes place.
# Python program to illustrate
# built-in method bool()
# Returns False as x is not equal to y
x=5
y = 10
print(bool(x==y))
# Returns False as x is None
x = None
print(bool(x))
# Returns False as x is an empty sequence
x = ()
print(bool(x))
# Returns False as x is an empty mapping
x = {}
print(bool(x))
# Returns False as x is 0
x = 0.0
print(bool(x))
# Returns True as x is a non empty string
x = 'DecentComputer'
print(bool(x))
23 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output
False
False
False
False
False
True
Boolean value from the expression
In this code, since a is assigned the value 10 and b is assigned the value 20, the Python
comparison a == b evaluates to False. Therefore, the code will output False.
# Declaring variables
a = 10
b = 20
# Comparing variables
print(a == b)
Output:
False
Integers and Floats as Booleans
Numbers can be used as bool values by using Python’s built-in bool() method. Any integer,
floating-point number, or complex number having zero as a value is considered as False, while if
they are having value as any positive or negative number then it is considered as True.
var1 = 0
print(bool(var1))
var2 = 1
print(bool(var2))
var3 = -9.7
print(bool(var3))
Output:
False
True
True
24 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Boolean Operators : Boolean Operations in Python are simple arithmetic of True and False
values. These values can be manipulated by the use of boolean operators which include AND,
Or, and NOT. Common boolean operations are –
• or
• and
• not
• == (equivalent)
• != (not equivalent)
Boolean OR Operator
The Boolean or operator returns True if any one of the inputs is True else returns False.
A B A or B
True True True
True False True
False True True
False False False
Python Boolean OR Operator
In the example, we have used a Python boolean with an if statement and OR operator that
checks if a is greater than b or b is smaller than c and it returns True if any of the conditions are
True (b<c in the above example).
# Python program to demonstrate
# or operator
a=1
b=2
c=4
if a > b or b < c:
print(True)
else:
print(False)
if a or b or c:
print("Atleast one number has boolean value as True")
Output
True
Atleast one number has boolean value as True
25 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Boolean And Operator
The Boolean operator returns False if any one of the inputs is False else returns True.
A B A and B
True True True
True False False
False True False
False False False
Python Boolean And Operator
In the first part of the code, the overall expression a > b and b < c evaluates to False. Hence, the
code will execute the else block and print False. Whereas in the second part, a is 0, conditions a
and b, and c will evaluate to False because one of the variables (a) has a boolean value of False.
Therefore, the code will execute the else block and print “At least one number has a boolean
value as False”.
# Python program to demonstrate
# and operator
a=0
b=2
c=4
if a > b and b<c:
print(True)
else:
print(False)
if a and b and c:
print("All the numbers has boolean value as True")
else:
print("Atleast one number has boolean value as False")
Output
False
Atleast one number has boolean value as False
26 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Boolean Not Operator
The Boolean Not operator only requires one argument and returns the negation of the argument
i.e. returns the True for False and False for True.
A Not A
True False
False True
Python Boolean Not Operator
The code demonstrates that when the value of a is 0, it is considered falsy, and the code block
inside the if statement is executed, printing the corresponding message.
# Python program to demonstrate
# not operator
a=0
if not a:
print("Boolean value of a is False")
Output
Boolean value of a is False
Boolean == (equivalent) and != (not equivalent) Operator
Both operators are used to compare two results. == (equivalent operator returns True if two
results are equal and != (not equivalent operator returns True if the two results are not same.
Python Boolean == (equivalent) and != (not equivalent) Operator
The code assigns values to variables a and b and then uses conditional statements to check if a is
equal to 0, if a is equal to b, and if a is not equal to b. It prints True for the first and third
conditions.
# Python program to demonstrate
# equivalent an not equivalent
# operator
a=0
b=1
27 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
if a == 0:
print(True)
if a == b:
print(True)
if a != b:
print(True)
Output
True
True
Python is Operator
The is keyword is used to test whether two variables belong to the same object. The test will
return True if the two objects are the same else it will return False even if the two objects are
100% equal.
Python is Operator
The code first assigns the value 10 to variables x and y. It then compares x and y using the “is”
operator and prints True because they refer to the same object. Next, it assigns two separate lists
to x and y. It then compares x and y using the “is” operator and prints False because the lists are
different objects in memory.
# Python program to demonstrate
# is keyword
x = 10
y = 10
if x is y:
print(True)
else:
print(False)
x = ["a", "b", "c", "d"]
y = ["a", "b", "c", "d"]
print(x is y)
Output
True
False
28 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Python in Operator
in operator checks for the membership i.e. checks if the value is present in a list, tuple, range,
string, etc.
Python in Operator
The code creates a list of animals and checks if the string “lion” is present in the list. If “lion” is
found in the list, it prints “True”.
# Python program to demonstrate
# in keyword
# Create a list
animals = ["dog", "lion", "cat"]
# Check if lion in list or not
if "lion" in animals:
print(True)
Output
True
TOPIC : 3(d) Python Lists
In Python, a list is a built-in data structure that is used to store an ordered collection of
items. Lists are mutable, meaning that their contents can be changed after the list has been
created. They can hold a various of data types, including integers, floats, strings, and even
other lists.
Let’s take a quick example for Python list:
a = [1, 'apple', 3.14, [5, 6]]
print(a)
Output
[1, 'apple', 3.14, [5, 6]]
Table of Content
• Creating a List
• Creating a List with Repeated Elements
• Accessing List Elements
• Modifying Lists
• Adding Elements into List
• Updating Elements into List
• Removing Elements from List
29 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
• Iterating Over Lists
• Nested Lists and Multidimensional Lists
Creating a List
We can create a list in Python using square brackets [] or by using the list() constructor. Here
are some common methods to create a list:
Using Square Brackets
We can directly create a list by enclosing elements in square brackets.
# List of integers
a = [1, 2, 3, 4, 5]
# List of strings
b = ['apple', 'banana', 'cherry']
# Mixed data types
c = [1, 'hello', 3.14, True]
print(a)
print(b)
print(c)
Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
Using the list() Constructor
We can also create a list by passing an iterable (like a string, tuple, or another list) to
the list() function.
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)
Output
[1, 2, 3, 'apple', 4.5]
30 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Creating a List with Repeated Elements
We can create a list with repeated elements using the multiplication operator.
# Create a list [2, 2, 2, 2, 2]
a = [2] * 5
# Create a list [0, 0, 0, 0, 0, 0, 0]
b = [0] * 7
print(a)
print(b)
Output
[2, 2, 2, 2, 2]
[0, 0, 0, 0, 0, 0, 0]
Accessing List Elements
Elements in a list can be accessed using indexing. Python indexes start at 0, so a[0] will access
the first element, while negative indexing allows us to access elements from the end of the list.
Like index -1 represents the last elements of list.
a = [10, 20, 30, 40, 50]
# Access first element
print(a[0])
# Access last element
print(a[-1])
Output
10
50
Adding Elements into List
We can add elements to a list using the following methods:
• append(): Adds an element at the end of the list.
• extend(): Adds multiple elements to the end of the list.
• insert(): Adds an element at a specific position.
# Initialize an empty list
a = []
# Adding 10 to end of list
31 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
[Link](10)
print("After append(10):", a)
# Inserting 5 at index 0
[Link](0, 5)
print("After insert(0, 5):", a)
# Adding multiple elements [15, 20, 25] at the end
[Link]([15, 20, 25])
print("After extend([15, 20, 25]):", a)
Output
After append(10): [10]
After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]
Updating Elements into List
We can change the value of an element by accessing it using its index.
a = [10, 20, 30, 40, 50]
# Change the second element
a[1] = 25
print(a)
Output
[10, 25, 30, 40, 50]
Removing Elements from List
We can remove elements from a list using:
• remove(): Removes the first occurrence of an element.
• pop(): Removes the element at a specific index or the last element if no index is specified.
• del statement: Deletes an element at a specified index.
a = [10, 20, 30, 40, 50]
# Removes the first occurrence of 30
[Link](30)
print("After remove(30):", a)
32 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# Removes the element at index 1 (20)
popped_val = [Link](1)
print("Popped element:", popped_val)
print("After pop(1):", a)
# Deletes the first element (10)
del a[0]
print("After del a[0]:", a)
Output
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]
After del a[0]: [40, 50]
Iterating Over Lists
We can iterate the Lists easily by using a for loop or other iteration methods. Iterating over lists is
useful when we want to do some operation on each item or access specific items based on
certain conditions. Let’s take an example to iterate over the list using for loop.
Using for Loop
a = ['apple', 'banana', 'cherry']
# Iterating over the list
for item in a:
print(item)
Output
apple
banana
cherry
Nested Lists and Multidimensional Lists
A nested list is a list within another list, which is useful for representing matrices or tables. We
can access nested elements by chaining indexes.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
33 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# Access element at row 2, column 3
print(matrix[1][2])
Output
6
How To Find the Length of a List in Python
The length of a list refers to the number of elements in the list. The simplest and most common
way to do this is by using the len() function. Let’s take an example.
Using len()
The len() function is the simplest and most efficient way to find the length of a list in Python.
It’s an inbuilt function that can be used on any sequence or collection, including lists.
a = [1, 2, 3, 4, 5]
length = len(a)
print(length)
Output
5
Find Maximum of two numbers Using max() function
This function is used to find the maximum of the values passed as its arguments.
Example:
# Python program to find the
# maximum of two numbers
a=2
b=4
maximum = max(a, b)
print(maximum)
Output
4
Using min() function This function is used to find the minimum of the values passed as its
arguments. Example:
# Python program to find the
34 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# minimum of two numbers
a=2
b=4
minimum = min(a, b)
print(minimum)
Output
2
Check if element exists in list in Python
Lists are a common data structure in Python, and a very frequent operation are are used on it is
to check if an element exists in a list.
The simplest way to check for the presence of an element in a list is using the in Keyword. This
method is readable, efficient, and works well for most use cases. Lets take an example:
a = [10, 20, 30, 40, 50]
# Check if 30 exists in the list
if 30 in a:
print("Element exists in the list")
else:
print("Element does not exist")
Output
Element exists in the list
Ways to remove duplicates from list in Python
The simplest way to remove duplicates is by converting a list to a set.
Using set() to Remove Duplicates
We can use set() to remove duplicates from list. However, this approach does not preserve the
original order.
a = [1, 2, 2, 3, 4, 4, 5]
# Remove duplicates by converting to a set
a = list(set(a))
print(a)
Output
[1, 2, 3, 4, 5]
35 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Explanation:
• Convert the list to a set to remove duplicates.
• Convert the set back to a list to maintain the list structure.
Note: Using set() removes duplicates but does not guarantee the order of elements.
Reversing a List in Python
The simplest way to reverse a list is by using the reverse() method.
Let’s take an example to reverse a list using reverse() method.
The reverse() method reverses the elements of the list in-place and it modify the original list
without creating a new list. This method is efficient because it doesn’t create a new list.
a = [1, 2, 3, 4, 5]
# Reverse the list in-place
[Link]()
print(a)
Output
[5, 4, 3, 2, 1]
Python program to find sum of elements in list
The simplest and quickest way to do this is by using the sum() function.
Using sum()
The sum() function is a built-in method to sum all elements in a list.
a = [10, 20, 30, 40]
res = sum(a)
print(res)
Output
100
Merge Two Lists in Python
Python provides several approaches to merge two lists. The simplest way to merge two lists is
by using the + operator.
Let’s take an example to merge two lists using + operator.
a = [1, 2, 3]
b = [4, 5, 6]
# Merge the two lists and assign
# the result to a new list
c=a+b
print(c)
36 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output
[1, 2, 3, 4, 5, 6]
Explanation: The + operator creates a new list by concatenating a and b. This operation does not
modify the original lists but returns a new combined list.
TOPIC : 3 (e) Python Tuples
Python Tuple is a collection of Python Programming objects much like a list. The sequence of
values stored in a tuple can be of any type, and they are indexed by integers. Values of a tuple
are syntactically separated by ‘commas‘. Although it is not necessary, it is more common to
define a tuple by closing the sequence of values in parentheses. This helps in understanding the
Python tuples more easily.
Creating a Tuple
In Python Programming, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping the data sequence.
Note: Creation of Python tuple without the use of parentheses is known as Tuple Packing.
Python Program to Demonstrate the Addition of Elements in a Tuple.
# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
# Creating a Tuple
# with the use of string
Tuple1 = ('Decent', 'Computer')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('Decent')
print("\nTuple with the use of function: ")
print(Tuple1)
37 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
Initial empty Tuple:
()
Tuple with the use of String:
('Decent', 'Computer')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('D', 'e', 'c', 'e', 'n', 't')
Creating a Tuple with Mixed Datatypes.
Python Tuples can contain any number of elements and of any datatype (like strings, integers,
list, etc.). Tuples can also be created with a single element, but it is a bit tricky. Having one
element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
# Creating a Tuple
# with Mixed Datatype
Tuple1 = (5, 'Welcome', 7, 'Decent')
print("\nTuple with Mixed Datatypes: ")
print(Tuple1)
# Creating a Tuple with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'Decent’)
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
# Creating a Tuple with repetition
Tuple1 = ('Decent',) * 3
print("\nTuple with repetition: ")
print(Tuple1)
# Creating a Tuple with the use of loop
Tuple1 = ('Decent')
n=5
print("\nTuple with a loop")
for i in range(int(n)):
Tuple1 = (Tuple1,)
print(Tuple1)
38 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
Tuple with Mixed Datatypes:
(5, 'Welcome', 7, 'Decent')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'Decent'))
Tuple with repetition:
('Decent', 'Decent', 'Decent')
Tuple with a loop
('Decent',)
(('Decent',),)
((('Decent',),),)
(((('Decent',),),),)
((((('Decent',),),),),)
Python Tuple Operations
Here, below are the Python tuple operations.
• Accessing of Python Tuples
• Concatenation of Tuples
• Slicing of Tuple
• Deleting a Tuple
Accessing of Tuples
In Python Programming, Tuples are immutable, and usually, they contain a sequence of
heterogeneous elements that are accessed via unpacking or indexing (or even by attribute in the
case of named tuples). Lists are mutable, and their elements are usually homogeneous and are
accessed by iterating over the list.
Note: In unpacking of tuple number of variables on the left-hand side should be equal to a
number of values in given tuple a.
# Accessing Tuple
# with Indexing
Tuple1 = tuple("Decent")
print("\nFirst element of Tuple: ")
print(Tuple1[0])
# Tuple unpacking
Tuple1 = ("Decent", "For", "Python")
39 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# This line unpack
# values of Tuple1
a, b, c = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
Output:
First element of Tuple:
D
Values after unpacking:
Decent
For
Python
Concatenation of Tuples
Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done by the
use of ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple.
Other arithmetic operations do not apply on Tuples.
Note- Only the same datatypes can be combined with concatenation, an error arises if a list and a
tuple are combined.
# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Decent', 'For', 'Python')
Tuple3 = Tuple1 + Tuple2
# Printing first Tuple
print("Tuple 1: ")
print(Tuple1)
# Printing Second Tuple
print("\nTuple2: ")
print(Tuple2)
# Printing Final Tuple
print("\nTuples after Concatenation: ")
print(Tuple3)
40 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
Tuple 1:
(0, 1, 2, 3)
Tuple2:
('Decent', 'For', 'Python')
Tuples after Concatenation:
(0, 1, 2, 3, 'Decent', 'For', 'Python')
Slicing of Tuple
Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple. Slicing
can also be done to lists and arrays. Indexing in a list results to fetching a single element
whereas Slicing allows to fetch a set of elements.
Note- Negative Increment values can also be used to reverse the sequence of Tuples.
# Slicing of a Tuple
# Slicing of a Tuple with Numbers
Tuple1 = tuple('DECENTFORPYTHON')
# Removing First element
print("Removal of First Element: ")
print(Tuple1[1:])
# Reversing the Tuple
print("\nTuple after sequence of Element is reversed: ")
print(Tuple1[::-1])
# Printing elements of a Range
print("\nPrinting elements between Range 4-9: ")
print(Tuple1[4:9])
Output:
Removal of First Element:
('E', 'C', 'E', 'N', 'T', 'F', 'O', 'R', 'P', 'Y', 'T', 'H', 'O', 'N')
Tuple after sequence of Element is reversed:
('N', 'O', 'H', 'T', 'Y', 'P', 'R', 'O', 'F', 'T', 'N', 'E', 'C', 'E', 'D')
Printing elements between Range 4-9:
('N', 'T', 'F', 'O', 'R')
41 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple gets
deleted by the use of del() method.
Note- Printing of Tuple after deletion results in an Error.
# Deleting a Tuple
Tuple1 = (0, 1, 2, 3, 4)
del Tuple1
print(Tuple1)
Output
Traceback (most recent call last):
File "/home/[Link]", line 7, in
print(Tuple1)
NameError: name 'Tuple1' is not defined
TOPIC : 3(f) Python Sets
Python Set is an unordered collection of data types that is iterable, mutable, and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method
for checking whether a specific element is contained in the set. Here, we will see what is a set in
Python and also see different examples of set Python.
Creating a Set in Python
Python Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by a ‘comma’.
Note: A Python set cannot have mutable elements like a list or dictionary, as it is immutable.
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
# Creating a Set with the use of a String
set1 = set("DecentForPython”)
print("\nSet with the use of String: ")
print(set1)
42 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
String = 'DecentForPython'
set1 = set(String)
print("\nSet with the use of an Object: ")
print(set1)
# Creating a Set with the use of a List
set1 = set(["Decent", "For", "Python"])
print("\nSet with the use of List: ")
print(set1)
# Creating a Set with the use of a tuple
t = ("Decent", "for", "Python")
print("\nSet with the use of Tuple: ")
print(set(t))
# Creating a Set with the use of a dictionary
d = {"Decent": 1, "for": 2, "Python": 3}
print("\nSet with the use of Dictionary: ")
print(set(d))
Ouput
Initial blank Set:
set()
Set with the use of String:
{'e', 'n', 'c', 'r', 'P', 't', 'o', 'F', 'y', 'D', 'h'}
Set with the use of an Object:
{'e', 'n', 'c', 'r', 'P', 't', 'o', 'F', 'y', 'D', 'h'}
Set with the use of List:
{'For', 'Python', 'Decent'}
Set with the use of Tuple:
{'for', 'Python', 'Decent'}
Set with the use of Dictionary:
{'for', 'Python', 'Decent'}
43 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
A Python set contains only unique elements but at the time of set creation, multiple duplicate
values can also be passed. Order of elements in a Python set is undefined and is unchangeable.
Type of elements in a set need not be the same, various mixed-up data type values can also be
passed to the set.
# Creating a Set with a List of Numbers
# (Having duplicate values)
set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5])
print("\nSet with the use of Numbers: ")
print(set1)
# Creating a Set with a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Decent', 4, 'For', 6, 'Python'])
print("\nSet with the use of Mixed Values")
print(set1)
Output
Set with the use of Numbers:
{1, 2, 3, 4, 5, 6}
Set with the use of Mixed Values
{1, 2, 4, 'Decent', 6, 'For', 'Python'}
Adding Elements to a Set in Python
Below are some of the approaches by which we can add elements to a set in Python:
• Using add() Method
• Using update() Method
Using add() Method
Elements can be added to the Sets in Python by using the built-in add() function. Only one
element at a time can be added to the set by using add() method, loops are used to add multiple
elements at a time with the use of add() method.
Note: Lists cannot be added to a set as elements because Lists are not hashable whereas Tuples
can be added because tuples are immutable and hence Hashable.
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
# Adding element and tuple to the Set
44 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
[Link](8)
[Link](9)
[Link]((6, 7))
print("\nSet after Addition of Three elements: ")
print(set1)
# Adding elements to the Set
# using Iterator
for i in range(1, 6):
[Link](i)
print("\nSet after Addition of elements from 1-5: ")
print(set1)
Output
Initial blank Set:
set()
Set after Addition of Three elements:
{8, 9, (6, 7)}
Set after Addition of elements from 1-5:
{1, 2, 3, (6, 7), 4, 5, 8, 9}
Using update() Method
For the addition of two or more elements, Update() method is used. The update() method accepts
lists, strings, tuples as well as other Python hash set as its arguments. In all of these cases,
duplicate elements are avoided.
# Addition of elements to the Set
# using Update function
set1 = set([4, 5, (6, 7)])
[Link]([10, 11])
print("\nSet after Addition of elements using Update: ")
print(set1)
Output
Set after Addition of elements using Update:
{4, 5, (6, 7), 10, 11}
45 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Accessing a Set in Python
Set items cannot be accessed by referring to an index, since sets are unordered the items has no
index. But you can loop through the Python hash set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.
# Creating a set
set1 = set(["Decent", "For", "Python"])
print("\nInitial set")
print(set1)
# Accessing element using
# for loop
print("\nElements of set: ")
for i in set1:
print(i, end=" ")
# Checking the element
# using in keyword
print("\n")
print("Decent" in set1)
Output
{'Python', 'Decent', 'For'}
Elements of set:
Python Decent For
True
Removing Elements from the Set in Python
Below are some of the ways by which we can remove elements from the set in Python:
• Using remove() Method or discard() Method
• Using clear() Method
Using remove() Method or discard() Method
Elements can be removed from the Sets in Python by using the built-in remove() function but a
KeyError arises if the element doesn’t exist in the hashset Python. To remove elements from a set
without KeyError, use discard(), if the element doesn’t exist in the set, it remains unchanged.
46 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(set1)
# Removing elements from Set using Remove() method
[Link](5)
[Link](6)
print("\nSet after Removal of two elements: ")
print(set1)
# Removing elements from Set using Discard() method
[Link](8)
[Link](9)
print("\nSet after Discarding two elements: ")
print(set1)
# Removing elements from Set using iterator method
for i in range(1, 5):
[Link](i)
print("\nSet after Removing a range of elements: ")
print(set1)
Output
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Set after Removal of two elements:
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}
Set after Discarding two elements:
{1, 2, 3, 4, 7, 10, 11, 12}
Set after Removing a range of elements:
{7, 10, 11, 12}
Using clear() Method
To remove all the elements from the set, clear() function is used.
47 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
#Creating a set
set1 = set([1,2,3,4,5])
print("\n Initial set: ")
print(set1)
# Removing all the elements from
# Set using clear() method
[Link]()
print("\nSet after clearing all the elements: ")
print(set1)
Output
Initial set:
{1, 2, 3, 4, 5}
Set after clearing all the elements:
set()
TOPIC : 3(g) Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs.
Example: Here, The data is stored in key: value pairs in dictionaries, which makes it easier to find
values.
Dict = {1: 'Decent', 2: 'For', 3: 'Python'}
print(Dict)
Output
{1: 'Decent', 2: 'For', 3: 'Python'}
Python dictionaries are essential for efficient data mapping and manipulation in programming. To
deepen your understanding of dictionaries and explore advanced techniques in data handling,
consider enrolling in our Complete Machine Learning & Data Science Program. This course
covers everything from basic dictionary operations to advanced data processing methods,
empowering you to become proficient in Python programming and data analysis.
Table of Content
• How to Create a Dictionary
• Different Ways to Create a Python Dictionary
• Nested Dictionaries
• Adding Elements to a Dictionary
48 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
• Accessing Elements of a Dictionary
• Accessing an Element of a Nested Dictionary
Python Dictionary Syntax
dict_var = {key1 : value1, key2 : value2, …..}
What is a Dictionary in Python?
Dictionaries in Python is a data structure, used to store values in key: value format. This makes it
different from lists, tuples, and arrays as in a dictionary each key has an associated value.
Note: As of Python version 3.7, dictionaries are ordered and can not contain duplicate keys.
How to Create a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within curly {} braces,
separated by a ‘comma’. The dictionary holds pairs of values, one being the Key and the other
corresponding pair element being its Key:value. Values in a dictionary can be of any data type
and can be duplicated, whereas keys can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
The code demonstrates creating dictionaries with different types of keys. The first dictionary uses
integer keys, and the second dictionary uses a mix of string and integer keys with corresponding
values. This showcases the flexibility of Python dictionaries in handling various data types as
keys.
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Output
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
49 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Dictionary Example
A dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing curly braces{}.
Different Ways to Create a Python Dictionary
The code demonstrates different ways to create dictionaries in Python. It first creates an empty
dictionary, and then shows how to create dictionaries using the dict() constructor with key-value
pairs specified within curly braces and as a list of tuples.
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = dict({1: 'Decent', 2: 'For', 3: 'Python'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, 'Decent'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Decent', 2: 'For', 3: 'Python'}
Dictionary with each item as a pair:
{1: 'Decent', 2: 'For'}
50 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Nested Dictionaries
DECENT
DECENT
Example: The code defines a nested dictionary named ‘Dict’ with multiple levels of key-value
pairs. It includes a top-level dictionary with keys 1, 2, and 3. The value associated with key 3 is
another dictionary with keys ‘A,’ ‘B,’ and ‘C.’ This showcases how Python dictionaries can be
nested to create hierarchical data structures.
Dict = {1: 'Decent', 2: 'For',
3: {'A': 'Welcome', 'B': 'To', 'C': 'Decent'}}
print(Dict)
Output
{1: 'Decent', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Decent'}}
Adding Elements to a Dictionary
The addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-in update() method.
Nested key values can also be added to an existing Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated otherwise a
new Key with the value is added to the Dictionary.
Example: Add Items to a Python Dictionary with Different DataTypes
The code starts with an empty dictionary and then adds key-value pairs to it. It demonstrates
adding elements with various data types, updating a key’s value, and even nesting dictionaries
within the main dictionary. The code shows how to manipulate dictionaries in Python.
51 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = 'Decent'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
Output
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Decent', 2: 'For', 3: 1}
Accessing Elements of a Dictionary
To access the items of a dictionary refer to its key name. Key can be used inside square brackets.
Access a Value in Python Dictionary
The code demonstrates how to access elements in a dictionary using keys. It accesses and prints
the values associated with the keys ‘name’ and 1, showcasing that keys can be of different data
types (string and integer).
Dict = {1: 'Decent', 'name': 'For', 3: 'Decent'}
print("Accessing a element using key:")
print(Dict['name'])
print("Accessing a element using key:")
print(Dict[1])
Output
Accessing a element using key:
For
Accessing a element using key:
Decent
52 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
There is also a method called get() that will also help in accessing the element from a dictionary.
This method accepts key as argument and returns the value.
Example: Access a Value in Dictionary using get() in Python
The code demonstrates accessing a dictionary element using the get() method. It retrieves and
prints the value associated with the key 3 in the dictionary ‘Dict’ . This method provides a safe
way to access dictionary values, avoiding KeyError if the key doesn’t exist.
Dict = {1: 'Decent', 'name': 'For', 3: 'Decent'}
print("Accessing a element using get:")
print([Link](3))
Output
Accessing a element using get:
Decent
Accessing an Element of a Nested Dictionary
To access the value of any key in the nested dictionary, use indexing [] syntax.
Example: The code works with nested dictionaries. It first accesses and prints the entire nested
dictionary associated with the key ‘Dict1’ . Then, it accesses and prints a specific value by
navigating through the nested dictionaries. Finally, it retrieves and prints the value associated
with the key ‘Name’ within the nested dictionary under ‘Dict2’ .
Dict = {'Dict1': {1: 'Decent'},
'Dict2': {'Name': 'For'}}
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output
{1: 'Decent'}
Decent
For
Deleting Elements using ‘del’ Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Example: The code defines a dictionary, prints its original content, and then uses
the ‘del’ statement to delete the element associated with key 1. After deletion, it prints the
updated dictionary, showing that the specified element has been removed.
53 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Dict = {1: 'Decent', 'name': 'For', 3: 'Decent'}
print("Dictionary =")
print(Dict)
del(Dict[1])
print("Data after deletion Dictionary=")
print(Dict)
Output
Dictionary =
{1: 'Decent', 'name': 'For', 3: 'Decent'}
Data after deletion Dictionary=
{'name': 'For', 3: 'Decent'}
TOPIC : 3(h) Python Arrays
What is an Array in Python?
An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together. This makes it easier to calculate the position of each
element by simply adding an offset to a base value, i.e., the memory location of the first element
of the array (generally denoted by the name of the array).
To get a detailed explanation of Python Array go through the Python Self Paced course , this
course offers you a complete fundamental of Python Array.
Create an Array in Python
Array in Python can be created by importing an array module. array( data_type , value_list ) is
used to create array in Python with data type and value list specified in its arguments.
In below code Python create array : one of integers and one of doubles . It then prints the
contents of each array to the console.
import array as arr
a = [Link]('i', [1, 2, 3])
print("The new created array is : ", end=" ")
Output
The new created array is : 1 2 3
54 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Accessing Elements from the Array
In order to access the array items refer to the index number. Use the index operator [ ] to access
an item in a array in Python. The index must be an integer.
Below, code shows first how to Python import array and use of indexing to access elements in
arrays. The a[0] expression accesses the first element of the array a , which is 1.
The a[3] expression accesses the fourth element of the array a , which is 4. Similarly,
the b[1] expression accesses the second element of the array b , which is 3.2, and
the b[2] expression accesses the third element of the array b , which is 3.3.
import array as arr
a = [Link]('i', [1, 2, 3, 4, 5, 6])
print("Access element is: ", a[0])
print("Access element is: ", a[3])
b = [Link]('d', [2.5, 3.2, 3.3])
print("Access element is: ", b[1])
print("Access element is: ", b[2])
Output
Access element is: 1
Access element is: 4
Access element is: 3.2
Access element is: 3.3
Removing Elements from the Array
Elements can be removed from the Python array by using built-in remove() function but an Error
arises if element doesn’t exist in the set. Remove() method only removes one element at a time,
to remove range of elements, iterator is used. pop() function can also be used to remove and
return an element from the array, but by default it removes only the last element of the array, to
remove element from a specific position of the array, index of the element is passed as an
argument to the pop() method.
Note – Remove method in List will only remove the first occurrence of the searched element.
Below, code shows how to Python import array, how to create, print, remove elements from, and
access elements of an array in Python. It imports the array module, which is used to work with
arrays. It creates an array of integers in and Python print arrays or prints the original array. It then
removes an element from the array and prints the modified array. Finally, it removes all
occurrences of a specific element from the array and prints the updated array
55 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
import array
arr = [Link]('i', [1, 2, 3, 1, 5])
print("The new created array is : ", end="")
for i in range(0, 5):
print(arr[i], end=" ")
print("\r")
print("The popped element is : ", end="")
print([Link](2))
print("The array after popping is : ", end="")
for i in range(0, 4):
print(arr[i], end=" ")
print("\r")
[Link](1)
print("The array after removing is : ", end="")
for i in range(0, 3):
print(arr[i], end=" ")
Output
The new created array is : 1 2 3 1 5
The popped element is : 3
The array after popping is : 1 2 1 5
The array after removing is : 2 1 5
Complexities for Removing elements in the Arrays
TOPIC : 3(i) Type Casting in Python (Implicit and Explicit) with Examples
Type Casting is the method to convert the Python variable datatype into a certain data type in
order to perform the required operation by users. In this article, we will see the various
techniques for typecasting. There can be two types of Type Casting in Python:
• Python Implicit Type Conversion
• Python Explicit Type Conversion
Implicit Type Conversion in Python
In this, method, Python converts the datatype into another datatype automatically. Users don’t
have to involve in this process.
56 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# Python program to demonstrate
# implicit type Casting
# Python automatically converts
# a to int
a=7
print(type(a))
# Python automatically converts
# b to float
b = 3.0
print(type(b))
# Python automatically converts
# c to float as it is a float addition
c=a+b
print(c)
print(type(c))
# Python automatically converts
# d to float as it is a float multiplication
d=a*b
print(d)
print(type(d))
Output:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
21.0
<class 'float'>
Explicit Type Conversion in Python
In this method, Python needs user involvement to convert the variable data type into the required
data type.
Python Convert Int to Float
Here, we are Converting Int to Float in Python with the float() function.
57 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# Python program to demonstrate
# type Casting
# int variable
a=5
# typecast to float
n = float(a)
print(n)
print(type(n))
Output:
5.0
<class 'float'>
Python Convert Float to Int
Here, we are Converting Float to int datatype in Python with int() function.
# Python program to demonstrate
# type Casting
# int variable
a = 5.9
# typecast to int
n = int(a)
print(n)
print(type(n))
Output:
5
<class 'int'>
Python Convert int to String
Here, we are Converting int to String datatype in Python with str() function.
# Python program to demonstrate
# type Casting
# int variable
a=5
# typecast to str
n = str(a)
print(n)
print(type(n))
58 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output:
5
<class 'str'>
Python Convert String to float
Here, we are casting string data type into float data type with float() function.
# Python program to demonstrate
# type Casting
# string variable
a = "5.9"
# typecast to float
n = float(a)
print(n)
print(type(n))
Output:
5.9
<class 'float'>
End of topic 3
59 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652