[go: up one dir, main page]

0% found this document useful (0 votes)
7 views84 pages

Python Notes - 3 Unit - 240606 - 123245

The document provides an overview of Python sets, explaining their characteristics such as being unordered, unchangeable, and not allowing duplicates. It covers how to create sets, including using the set() function and curly braces, as well as operations like adding, removing elements, and performing set operations like union and intersection. Additionally, it introduces frozen sets as immutable versions of sets and discusses various built-in methods for manipulating sets.

Uploaded by

akhilverma9580
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views84 pages

Python Notes - 3 Unit - 240606 - 123245

The document provides an overview of Python sets, explaining their characteristics such as being unordered, unchangeable, and not allowing duplicates. It covers how to create sets, including using the set() function and curly braces, as well as operations like adding, removing elements, and performing set operations like union and intersection. Additionally, it introduces frozen sets as immutable versions of sets and discusses various built-in methods for manipulating sets.

Uploaded by

akhilverma9580
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Python (Unit 3)

 Sets
Python Set is an unordered collection of data types that is iterable, mutable, and has no duplicate
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. The elements appear in an
arbitrary order when sets are iterated. Sets are commonly used for membership testing, removing
duplicates entries, and also for operations such as intersection, union, and set difference.

 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.

A Python set contains only unique elements but at the time of set creation, multiple duplicate
values can also be passed. Type of elements in a set need not be the same, various mixed-up data
type values can also be passed to the set.
Example:
# Creating a Set with a List of Numbers
# (Having duplicate values)

set1 = set([1, 2, 2, 4, 3, 3, 3, 6, 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, 'Goel', 4, 'For', 6, 'Gitm'])
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


{'Goel', 1, 2, 4, 'For', 6, 'Gitm'}

 Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.

 Unchangeable

Dr. Yusuf Perwej Page 1


Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
Once a set is created, you cannot change its items, but you can remove items and add new items.

 Duplicates Not Allowed


Sets cannot have two items with the same value.

Example:
Duplicate values will be ignored:
goel = {"apple", "banana", "cherry", "apple"}
print(goel)

Note: The values True and 1 are considered the same value in sets, and are treated as duplicates:

Example:
True and 1 is considered the same value:
goel = {"apple", "banana", "cherry", True, 1, 2}
print(goel)

Note: The values False and 0 are considered the same value in sets, and are treated as duplicates:

Example:
False and 0 is considered the same value:
goel= {"apple", "banana", "cherry", False, True, 0}
print(goel)

 Frozen Sets in Python

The frozen sets are the immutable version of the conventional sets, which means that the elements
in the frozen set cannot be changed. Sets are mutable and unhashable, therefore they cannot be
used as dictionary keys. Frozensets can be used as dictionary keys because they are hashable.

The frozenset() function can be used to construct frozensets. While elements of a set can be
modified at any time, elements of the frozen set remain the same after creation.

If no parameters are passed, it returns an empty frozenset.

Example:
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
print(x)

Output:
frozenset({'cherry', 'banana', 'apple'})

Example:
# Python program to demonstrate
# working of a FrozenSet

# Creating a Set
Lucknow = ('G', 'i', 't', 'm', 'G', 'o', 'e', 'l')

Dr. Yusuf Perwej Page 2


Fset1 = frozenset(Lucknow)
print("The FrozenSet is: ")
print(Fset1)

# To print Empty Frozen Set


# No parameter is passed
print("\nEmpty FrozenSet: ")
print(frozenset())

Output:
The FrozenSet is:
frozenset({'l', 't', 'e', 'o', 'i', 'm', 'G'})

Empty FrozenSet:
frozenset()
Example:
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
x[1] = "strawberry"
print(x)
Output:
Traceback (most recent call last):
File "demo_ref_frozenset2.py", line 3, in <module>
x[1] = "strawberry"
TypeError: 'frozenset' object does not support item assignment

Example:
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')

fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())

# frozensets are immutable


fSet.add('v')

Output:
The frozen set is: frozenset({'u', 'e', 'o', 'i', 'a'})
The empty frozen set is: frozenset()
ERROR!
Traceback (most recent call last):
File "<main.py>", line 9, in <module>
AttributeError: 'frozenset' object has no attribute 'add'

 Creating a Python Set with Another Method

In this example, a set is created by using curly braces {} notation, containing the number 1,2 and
3.

Example:
# Another Method to create sets in Python3
Dr. Yusuf Perwej Page 3
# Set containing numbers
my_set = {1, 2, 3}

print(my_set)

Output
{1, 2, 3}

 Set Operations and Methods

Python has a set of built-in methods that you can use on sets.

Method Shortcut Description


add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
Returns a set containing the difference between two or
difference() -
more sets
Removes the items in this set that are also included in
difference_update() -=
another, specified set
discard() Remove the specified item
intersection() & Returns a set, that is the intersection of two other sets
Removes the items in this set that are not present in
intersection_update() &=
other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() <= Returns whether another set contains this set or not
Returns whether all items in this set is present in other,
<
specified set(s)
issuperset() >= Returns whether this set contains another set or not
Returns whether all items in other, specified set(s) is
>
present in this set
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() ^ Returns a set with the symmetric differences of two sets
symmetric_difference_up Inserts the symmetric differences from this set and
^=
date() another
union() | Return a set containing the union of sets
update() |= Update the set with the union of this set and others

 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

Dr. Yusuf Perwej Page 4


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, but 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.

Example:
# Creating a Set
set1 = set()

# Adding element and tuple to the Set


set1.add(8)
set1.add(9)
set1.add((6, 7))
print("\nSet after Addition of Three elements: ")
print(set1)

# Adding elements to the Set


# using Iterator
for i in range(1, 6):
set1.add(i)
print("\nSet after Addition of elements from 1-5: ")
print(set1)

Output:
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

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.

Example:
# Addition of elements to the Set
# using Update function
set1 = set([4, 5, (6, 7)])
set1.update([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}

 Accessing a Set in Python

Dr. Yusuf Perwej Page 5


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.

Example:
# Creating a set
set1 = set(["Gitm", "For", "Goel"])
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("Gitm" in set1)

Output:
Initial set
{'Goel', 'For', 'Gitm'}

Elements of set:
Goel For Gitm

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 pop() 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.

Example:
# 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


set1.remove(5)
set1.remove(6)

Dr. Yusuf Perwej Page 6


print("\nSet after Removal of two elements: ")
print(set1)

# Removing elements from Set using Discard() method


set1.discard(8)
set1.discard(9)
print("\nSet after Discarding two elements: ")
print(set1)

# Removing elements from Set using iterator method


for i in range(1, 5):
set1.remove(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 pop() Method

Pop() function can also be used to remove and return an element from the set, but it removes
only the last element of the set.

Note: If the set is unordered then there’s no such way to determine which element is popped by
using the pop() function.

Example:
# Python program to demonstrate
# Deletion of elements in a Set

# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(set1)

# Removing element from the


# Set using the pop() method
set1.pop()
print("\nSet after popping an element: ")
print(set1)

Output:

Dr. Yusuf Perwej Page 7


Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Set after popping an element:


{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

 Using clear() Method

To remove all the elements from the set, clear() function is used.

Example:
#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
set1.clear()
print("\nSet after clearing all the elements: ")
print(set1)

Output:
Initial set:
{1, 2, 3, 4, 5}

Set after clearing all the elements:


set()

 Typecasting Objects into Sets


In this example, lists, strings and dictionaries are converted into sets using the set() constructor,
eliminating duplicates in lists and extracting unique elements in strings and dictionary keys.

Example:
# Typecasting list into set
my_list = [1, 2, 3, 3, 4, 5, 5, 6, 2]
my_set = set(my_list)
print("my_list as a set: ", my_set)

# Typecasting string into set


my_str = "GoelforGitms"
my_set1 = set(my_str)
print("my_str as a set: ", my_set1)

# Typecasting dictionary into set


my_dict = {1: "One", 2: "Two", 3: "Three"}
my_set2 = set(my_dict)
print("my_dict as a set: ", my_set2)

Output:

Dr. Yusuf Perwej Page 8


my_list as a set: {1, 2, 3, 4, 5, 6}
my_str as a set: {'G', 't', 'i', 'r', 's', 'o', 'm', 'f', 'e', 'l'}
my_dict as a set: {1, 2, 3}

 Set Union

The union of two sets is the set that contains all of the elements from both sets without
duplicates. To find the union of two Python sets, use the union() method or the | syntax.
Here is an example of how to perform a union set operation in python.

Example:
set1 = {11, 22, 33}
set2 = {33, 54, 75}
# Perform union operation using the `|` operator or the `union()` method
union_set = set1 | set2
# Or: union_set = set1.union(set2)
print(union_set)

Output:
{33, 22, 54, 75, 11}

Explanation: In this example, we have two sets set1 and set2. We can perform a union
operation using either the | operator or the union() method, which combines all the elements
from both sets and removes any duplicates.

 Set Intersection

The intersection of two sets is the set that contains all of the common elements of both sets. To
find the intersection of two Python sets, we can either use the intersection() method or &
operator.

Example:
set1 = {11, 22, 44}
set2 = {44, 54, 75}
# Perform intersection operation using the `&` operator or the `intersection()` method
intersection_set = set1 & set2
# Or: intersection_set = set1.intersection(set2)
print(intersection_set)

Output:
{44}

Explanation: In this example, we have two sets set1 and set2. We can perform an intersection
operation using either the & operator or the intersection () method, which returns a new set that
contains only the elements that are common to both set1 and set2. The resulting intersection_set
contains only element 33, which is present in both set1 and set2.

 Set Difference

The difference between the two sets is the set of all the elements in the first set that are not
present in the second set. To accomplish this, we can either use the difference() function or the –
operator in python.

Dr. Yusuf Perwej Page 9


Example:
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Using the difference() method
set3 = set1.difference(set2)
print(set3)
# Using the - operator
set4 = set1 - set2
print(set4)

Output:
{1, 2}
{1, 2}

Explanation: In this example, we have two sets set1 and set2 with some common elements. We
want to get the elements that are present in set1 but not in set2. We can achieve this by using the
difference() method or the – operator.

In the first approach, we use the difference() method of set1 and pass set2 as an argument. This
returns a new set set3 that contains the elements that are present in set1 but not in set2.
In the second approach, we use the – operator to perform the set difference operation. This is
equivalent to using the difference() method. The result is stored in the set4.

 Set Symmetric Difference

The symmetric difference between the two sets is the set containing all the elements that are
either in the first or second set but not in both. In Python, you can use either the symmetric
difference() function or the ^ operator to achieve this.

Example:
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Using the symmetric_difference() method
set3 = set1.symmetric_difference(set2)
print(set3)
# Using the ^ operator
set4 = set1 ^ set2
print(set4)

Output:
{1, 2, 6, 7}
{1, 2, 6, 7}

Explanation: In this example, we have two sets set1 and set2 with some common elements. We
want to get the elements that are present in either of the sets, but not in both. We can achieve this
by using the symmetric_difference() method or the ^ operator.

In the first approach, we use the symmetric_difference() method of set1 and pass set2 as an
argument. This returns a new set set3 that contains the elements that are present in either of the
sets, but not in both.

Dr. Yusuf Perwej Page 10


In the second approach, we use the ^ operator to perform the set symmetric difference operation.
This is equivalent to using the symmetric_difference() method. The result is stored in the set4.

 Issubset

The issubset() operation is used in Python to check whether a set is a subset of another set.

Example:
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4}
# Check if set2 is a subset of set1
print(set2.issubset(set1))
# Check if set1 is a subset of set2
print(set1.issubset(set2))

Output:
True
False

Explanation: In this example, we have two sets set1 and set2. We want to check if set2 is a
subset of set1. We can do this by calling the issubset() method of set2 and passing set1 as an
argument. This returns a boolean value True, which indicates that set2 is a subset of set1.
Next, we check if set1 is a subset of set2 by calling the issubset() method of set1 and passing
set2 as an argument. This returns a boolean value False, which indicates that set1 is not a subset
of set2.

 Issuperset

The issuperset() operation in Python is used to check whether a set is a superset of another set. A
superset is a set that contains all the elements of another set.

Example:
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4}
# Check if set1 is a superset of set2
print(set1.issuperset(set2))
# Check if set2 is a superset of set1
print(set2.issuperset(set1))

Output:
True
False

Explanation: In this example, we have two sets set1 and set2. We want to check if set1 is a
superset of set2. We can do this by calling the issuperset() method of set1 and passing set2 as an
argument. This returns a boolean value True, which indicates that set1 is a superset of set2. Next,
we check if set2 is a superset of set1 by calling the issuperset() method of set2 and passing set1 as
an argument. This returns a boolean value False, which indicates that set2 is not a superset of set1.

 Isdisjoint

Dr. Yusuf Perwej Page 11


The isdisjoint() operation in Python is used to check whether two sets have any common
elements. If the two sets have no common elements, then they are said to be disjoint.

Example:
set1 = {1, 2, 3, 4, 5}
set2 = {6, 7, 8}
# Check if set1 and set2 are disjoint
print(set1.isdisjoint(set2))
set3 = {4, 5, 6}
set4 = {6, 7, 8}
# Check if set3 and set4 are disjoint
print(set3.isdisjoint(set4))

Output:
True
False

Explanation: The isdisjoint() method in Python is used to check whether two sets have any
common elements. If the two sets have no common elements, then they are said to be disjoint.

 Tuples

A tuple is a data structure comprised of comma-separated values. Unlike dictionaries, which are
unordered and mutable, tuples are immutable and their elements are ordered by insertion (similar
to lists). Tuple elements can be of different data types.

 Tuples are an immutable data type, meaning their elements cannot be changed after they
are generated.
 Each element in a tuple has a specific order that will never change because tuples are
ordered sequences.
 All the objects-also known as "elements"-must be separated by a comma, enclosed in
parenthesis (). Although parentheses are not required, they are recommended.
 Any number of items, including those with various data types (dictionary, string, float,
list, etc.), can be contained in a tuple.

Example:

# Python program to show how to create a tuple


# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)

# Creating tuple having integers


int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types


mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)

# Creating a nested tuple

Dr. Yusuf Perwej Page 12


nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)

Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Example:
# Python program to create a tuple without using parentheses
# Creating a tuple
tuple= 4, 10.7, "Tuples", ["Python", "Goel"]
# Displaying the tuple created
print(tuple)

Output:
(4, 10.7, 'Tuples', ['Python', 'Goel'])

 Immutable in Tuples

Tuples in Python are similar to Python lists but not entirely. Tuples are immutable and ordered
and allow duplicate values. Some Characteristics of Tuples in Python.
 We can find items in a tuple since finding any item does not make changes in the tuple.
 One cannot add items to a tuple once it is created.
 Tuples cannot be appended or extended.
 We cannot remove items from a tuple once it is created.

Example:
mytuple = (1, 2, 3, 4, 5)

# tuples are indexed


print(mytuple[1])
print(mytuple[4])

# tuples contain duplicate elements


mytuple = (1, 2, 3, 4, 2, 3)
print(mytuple)

# adding an element
mytuple[1] = 100
print(mytuple)

Output:
Python tuples are ordered and we can access their elements using their index values. They are
also immutable, i.e., we cannot add, remove and change the elements once declared in the tuple,
so when we tried to add an element at index 1, it generated the error.
2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 11, in

Dr. Yusuf Perwej Page 13


tuple1[1] = 100
TypeError: 'tuple' object does not support item assignment

 Accessing Values in Python Tuples

Tuples in Python provide two ways by which we can access the elements of a tuple.
 Using a positive index
 Using a negative index

 Python Access Tuple using a Positive Index

Using square brackets we can get the values from tuples in Python.

Example:
var = ("Goels", "for", "Gitms")
print("Value in Var[0] = ", var[0])
print("Value in Var[1] = ", var[1])
print("Value in Var[2] = ", var[2])

Output:
Value in Var[0] = Goels
Value in Var[1] = for
Value in Var[2] = Gitms

 Access Tuple using Negative Index

In the above methods, we use the positive index to access the value in Python, and here we will
use the negative index within [].

Example:
var = (1, 2, 3)
print("Value in Var[-1] = ", var[-1])
print("Value in Var[-2] = ", var[-2])
print("Value in Var[-3] = ", var[-3])

Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1

 Different Operations Related to Tuples

Below are the different operations related to tuples in Python:


 Concatenation
 Nesting
 Repetition
 Slicing
 Deleting
 Finding the length
 Multiple Data Types with tuples
 Conversion of lists to tuples
 Tuples in a Loop

Dr. Yusuf Perwej Page 14


 Concatenation of Python Tuples

To Concatenation of Python Tuples, we will use plus operators(+).

Example:
# Code for concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'gitm')
# Concatenating above two
print(tuple1 + tuple2)

Output:
(0, 1, 2, 3, 'python', 'gitm')

 Nesting of Python Tuples

A nested tuple in Python means a tuple inside another tuple.


Example:
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'gitm')
tuple3 = (tuple1, tuple2)
print(tuple3)

Output :
((0, 1, 2, 3), ('python', 'gitm'))

 Repetition Python Tuples

We can create a tuple of multiple same elements from a single element in that tuple.

Example:
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)

Output:
('python', 'python', 'python')
Try the above without a comma and check. You will get tuple3 as a string
‘pythonpythonpython’.

 Slicing Tuples in Python

Slicing a Python tuple means dividing a tuple into small tuples using the indexing method.

Example:
# code to test slicing
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])

Dr. Yusuf Perwej Page 15


Output:
In this example, we sliced the tuple from index 1 to the last element. In the second print
statement, we printed the tuple using reverse indexing. And in the third print statement, we
printed the elements from index 2 to 4.
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)

Note: In Python slicing, the end index provided is not included.

 Deleting a Tuple in Python

In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of
error because after deleting the tuple, it will give a NameError.

Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using
Del keyword.

Example:

# Code for deleting a tuple


tuple3 = ( 0, 1)
del tuple3
print(tuple3)

Output:
Traceback (most recent call last):
File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
print(tuple3)
NameError: name 'tuple3' is not defined

 Finding the Length of a Python Tuple

To find the length of a tuple, we can use Python’s len() function and pass the tuple as the
parameter.

Example:
# Code for printing the length of a tuple
tuple2 = ('python', 'gitm')
print(len(tuple2))

Output:
2
 Multiple Data Types With Tuple

Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple
datatypes.

Example:
# tuple with different datatypes
tuple_obj = ("immutable",True,23)

Dr. Yusuf Perwej Page 16


print(tuple_obj)

Output :
('immutable', True, 23)

 Converting a List to a Tuple

We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as
its parameters.

Example:
# Code for converting a list and a string into a tuple
list1 = [0, 1, 2]
print(tuple(list1))
# string 'python'
print(tuple('python'))

Output:
Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are
taken as elements), and converts them to a tuple.
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')

 Tuples in a Loop

We can also create a tuple with a single element in it using loops.

Example:
# python code for creating tuples in a loop
tup = ('gitm',)
# Number of time loop runs
n=5
for i in range(int(n)):
tup = (tup,)
print(tup)

Output:
(('gitm',),)
((('gitm',),),)
(((('gitm',),),),)
((((('gitm',),),),),)
(((((('gitm',),),),),),)

 tuples Operations and Methods

Python has two built-in methods that you can use on tuples.

Method Description
count() Returns the number of times a specified value occurs in a tuple

Dr. Yusuf Perwej Page 17


Searches the tuple for a specified value and returns the position of where it
index()
was found

 Count() Method

The count() method of Tuple returns the number of times the given element appears in the tuple.

Syntax:
tuple.count(element)
Where the element is the element that is to be counted.

Example 1: Using the Tuple count() method


# Creating tuples
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
Tuple2 = ('python', 'geek', 'python',
'for', 'java', 'python')

# count the appearance of 3


res = Tuple1.count(3)
print('Count of 3 in Tuple1 is:', res)

# count the appearance of python


res = Tuple2.count('python')
print('Count of Python in Tuple2 is:', res)

Output:
Count of 3 in Tuple1 is: 3
Count of Python in Tuple2 is: 3

Example 2: Counting tuples and lists as elements in Tuples

# Creating tuples
Tuple = (0, 1, (2, 3), (2, 3), 1,
[3, 2], 'gitms', (0,))

# count the appearance of (2, 3)


res = Tuple.count((2, 3))
print('Count of (2, 3) in Tuple is:', res)

# count the appearance of [3, 2]


res = Tuple.count([3, 2])
print('Count of [3, 2] in Tuple is:', res)

Output:
Count of (2, 3) in Tuple is: 2
Count of [3, 2] in Tuple is: 1

 Index() Method

The Index() method returns the first occurrence of the given element from the tuple.

Syntax:

Dr. Yusuf Perwej Page 18


tuple.index(element, start, end)

Parameters:
 element: The element to be searched.
 start (Optional): The starting index from where the searching is started
 end (Optional): The ending index till where the searching is done

Note: This method raises a ValueError if the element is not found in the tuple.

Example 1: Using Tuple Index() Method


# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)

# getting the index of 3


res = Tuple.index(3)
print('First occurrence of 3 is', res)

# getting the index of 3 after 4th


# index
res = Tuple.index(3, 4)
print('First occurrence of 3 after 4th index is:', res)

Output:
First occurrence of 3 is 3
First occurrence of 3 after 4th index is: 5

Example 2: Using Tuple() method when the element is not found


# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)

# getting the index of 3


res = Tuple.index(4)

Output:
ValueError: tuple.index(x): x not in tuple

 Function in tuple

 The len() Function

This function returns the number of elements present in a tuple. Moreover, it is necessary to
provide a tuple to the len() function.

Example:
tup = (22, 45, 23, 78, 6.89)

len(tup)

Output:
5

Dr. Yusuf Perwej Page 19


 The count() Function

This function will help us to fund the number of times an element is present in the tuple.
Furthermore, we have to mention the element whose count we need to find, inside the count
function.

Example:
tup = (22, 45, 23, 78, 22, 22, 6.89)

tup.count(22)

Output:
3

Example:
tup.count(54)

Output:
0

 The index() Function

The tuple index() method helps us to find the index or occurrence of an element in a tuple. This
function basically performs two functions:

Giving the first occurrence of an element in the tuple.


Raising an exception if the element mentioned is not found in the tuple.

Example: Finding the index of an element


tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
print(tup.index(45))
print(tup.index(890))

Output:
#prints the index of elements 45 and 890

Example:
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
print(tup.index(3.2))

Output:
# gives an error because the element is not present in the tuple.

ValueError: tuple.index(x): x not in tuple

 The sorted() Function

Dr. Yusuf Perwej Page 20


This method takes a tuple as an input and returns a sorted list as an output. Moreover, it does not
make any changes to the original tuple.

Example:

tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

x = sorted(tup)

print (x)

[1, 2, 2.4, 3, 4, 22, 45, 56, 890]

 The min(), max(), and sum() Tuple Functions

min(): gives the smallest element in the tuple as an output. Hence, the name is min().

Example:

tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

x = min(tup)

print (x)

max(): gives the largest element in the tuple as an output. Hence, the name is max().

Example:

tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

x = max(tup)

print (x)

sum(): gives the sum of the elements present in the tuple as an output.

Example:

a = (1, 2, 3, 4, 5)
x = sum(a)
print(x)

 String data type and string operations,

Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes. The computer does not understand the characters; internally, it stores manipulated
character as the combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say that Python strings
are also called the collection of Unicode characters.

Dr. Yusuf Perwej Page 21


In Python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.

Syntax:
str = "Hi Goel"

Here, if we check the type of the variable str using a Python script

print(type(str)), then it will print a string (str).

In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string of
length 1.

 Creating String in Python

We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string.

Example:
#Using single quotes
str1 = 'Hello Goel'
print(str1)
#Using double quotes
str2 = "Hello Goel"
print(str2)
#Using triple quotes
str3 = '''''Triple quotes are generally used for
represent the multiline or
Goel'''
print(str3)

Output:
Hello Goel
Hello Goel
Triple quotes are generally used for
represent the multiline or
Goel

String Operators

Operator Description
It is known as concatenation operator used to join the strings given either side of the
+
operator.
It is known as repetition operator. It concatenates the multiple copies of the same
*
string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
It is known as range slice operator. It is used to access the characters from the specified
[:]
range.
It is known as membership operator. It returns if a particular sub-string is present in
in
the specified string.

Dr. Yusuf Perwej Page 22


It is also a membership operator and does the exact reverse of in. It returns true if a
not in
particular substring is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to
r/R print the actual meaning of escape characters such as "C://python". To define any
string as a raw string, the character r or R is followed by the string.
It is used to perform string formatting. It makes use of the format specifiers used in C
% programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.
Example
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello

Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

 Operations on String

String handling in python probably requires least efforts. Since in python, string operations have
very low complexity compared to other languages. Let's see how we can play around with
strings.

 Concatenation: No, wait! what? This word may sound a bit complex for absolute
beginners but all it means is - to join two strings.

Example:
print ("Hello" + "World");

Output:
HelloWorld

Yes. A plus sign + is enought to do the trick. When used with strings, the + sign joins the two
strings.

Example:
s1 = "Name Python "
s2 = "had been adapted "
Dr. Yusuf Perwej Page 23
s3 = "from Monty Python"
print (s1 + s2 + s3)

Output:
Name Python had been adapted from Monty Python

 Repetition: Suppose we want to write same text multiple times on console. Like repeat
"Hi!" a 100 times. Now one option is to write it all manually, like "Hi!Hi!Hi!..."
hundred times or just do the following:
print ("Hi!"*100)

Suppose, you want the user to input some number n and based on that you want a text to be
printed on console n times, how can you do it? It's simple. Just create a variable n and use input()
function to get a number from the user and then just multiply the text with n.

n = input("Number of times you want the text to repeat: ")

Number of times you want the text to repeat: 5

print ("Text"*n);

TextTextTextTextText

Check existence of a character or a sub-string in a string: The keyword in is used for this.
For example: If there is a text India won the match and you want to check if won exist in it or
not. Go to IDLE and try the following:
>>> "won" in "India won the match"

True

 Amongst other datatypes in python, there is Boolean datatype which can have one of the
possible two values, i.e., either true or false. Since we are checking if something exists in
a string or not, hence, the possible outcomes to this will either be Yes, it exists or No, it
doesn't, therefore either True or False is returned. This should also give you an idea
about where to use Boolean datatype while writing programs.

not in keyword: This is just the opposite of the in keyword. You're pretty smart if you guessed
that right. Its implementation is also pretty similar to the in keyword.
>>> "won" not in "India won the match"

False

You can see all the above String operations live in action, by clicking on the below Live
example button. Also, we suggest you to practice using the live compiler and try changing the
code and run it.

 Converting String to Int or Float datatype and vice versa

This is a very common doubt amongst beginners as a number when enclosed in quotes becomes
a string in python and then if you will try to perform mathematical operations on it, you will get
error.

numStr = '123'
Dr. Yusuf Perwej Page 24
In the statement above 123 is not a number, but a string.

Hence, in such situation, to convert a numeric string into float or int datatype, we can use float()
and int() functions.

numStr = '123'
numFloat = float(numStr)
numInt = int(numFloat)

And then you can easily perform mathematical functions on the numeric value.

Similarly, to convert an int or float variable to string, we can use the str() function.

num = 123
# so simple
numStr = str(num)
 Slicing

Slicing is yet another string operation. Slicing lets you extract a part of any string based on a
start index and an end index. First lets get familiar with its usage syntax:

string_name [starting_index : finishing_index : character_iterate]

 String_name is the name of the variable holding the string.


 starting_index is the index of the beginning character which you want in your sub-
string.
 finishing_index is one more than the index of the last character that you want in your
substring.
 character_iterate: To understand this, let us consider that we have a string Hello
Brother!, and we want to use the slicing operation on this string to extract a sub-string.
This is our code:

Example:
str = "Hello Brother!"
print(str[0:10:2]);

output:
Hlobo

 Now str [0:10:2] means, we want to extract a substring starting from the index 0
(beginning of the string), to the index value 10, and the last parameter means, that we
want every second character, starting from the starting index. Hence in the output we will
get, HloBo.

H is at index 0, then leaving e, the second character from H will be printed, which is l,
then skipping the second l, the second character from the first l is printed, which is o and
so on.

It will be more clear with a few more examples:

Let's take a string with 10 characters, ABCDEFGHIJ. The index number will begin from 0 and
end at 9.
Dr. Yusuf Perwej Page 25
A B C D E F G H I J

0 1 2 3 4 5 6 7 8 9

Example:
s = "ABCDEFGHIJ"
print s[0:5:1]

Output:
ABCDE

Here slicing will be done from 0th character to the 4th character (5-1) by iterating 1 character in
each jump.

Now, remove the last number and the colon and just write this.

print (s[0:5]);

Output:
ABCDE

Example:
# String Slicing
str = "TCSion Python Test"
print (str[1:18:2])

# You can use String slicing to accomplish


# amazing tasks. You just have to be a little clever

# we can even provide only the start and end


newStr = "Studytonight"
print (newStr[5:12])

Output:
CinPto et
tonight

 The split() Method

The split() method divides a string into a list where each word is an item. Here’s how you can
use split():

my_string = 'Hello, Python!'


print(my_string.split())

Output:
['Hello,', 'Python!']

In the above example, we split my_string into a list of words using the split() method. The
output is a list with two items: ‘Hello,’ and ‘Python!’.
Dr. Yusuf Perwej Page 26
 The replace() Method

The replace() method replaces a specified phrase with another specified phrase. Here’s how you
can use replace():

my_string = 'Hello, Python!'


print(my_string.replace('Python', 'World'))

Output:
'Hello, World!'

In the above example, we replace ‘Python’ with ‘World’ in my_string using the replace()
method. The output is ‘Hello, World!’.

 Alternate Tools for String Manipulation

Python provides a wealth of built-in functionality for string manipulation, but there are also
several alternative approaches that can offer more flexibility or efficiency in certain scenarios.
Let’s take a look at two of these: regular expressions and third-party libraries.

Regular Expressions in Python

Regular expressions (regex) provide a powerful way to match and manipulate strings based on
patterns. Python’s re module supports regex operations.

Here’s an example where we use a regular expression to find all the words in a string:

import re

my_string = 'Hello, Python! How are you doing?'


words = re.findall(r'\b\w+\b', my_string)
print(words)

# Output:
# ['Hello', 'Python', 'How', 'are', 'you', 'doing']
Python

In the above example, we use the findall() function from the re module to find all words in
my_string. The output is a list of words in the string.

 Python String Methods and Formatting

Python provides a wealth of built-in methods for string manipulation. These methods allow you
to transform, search, split, replace, and perform many other operations on strings.

Here’s an example of using the upper() method to convert a string to uppercase:

my_string = 'Hello, Python!'


print(my_string.upper())

# Output:
# 'HELLO, PYTHON!'

Dr. Yusuf Perwej Page 27


In the above example, we convert my_string to uppercase using the upper() method. The output
is ‘HELLO, PYTHON!’.

Python also supports several ways to format strings, including f-strings and the format() method.
These techniques allow you to insert variables into strings, align text, set precision, and more.

Here’s an example of using an f-string to insert a variable into a string:

name = 'Python'
greeting = f'Hello, {name}!'
print(greeting)

# Output:
# 'Hello, Python!'

In the above example, we use an f-string to insert the variable name into the string greeting. The
output is ‘Hello, Python!’.

Understanding these fundamental concepts can help you work more effectively with Python
strings and leverage their full power in your Python scripts.

 Defining list and list slicing

A Python list is a mutable collection of heterogeneous elements (items) under one variable name.
A Python list is a collection of zero or more elements. In this context, mutability means the
elements inside a list can be changed while the program is running.

We also can add or remove elements from a list whenever we want. In Python, we define lists by
enclosing the elements between square brackets and separating them with commas. Each list’s
element has an index representing the element's position in the list with a starting index of zero.

variable_name = [item1, item2, item3, … , itemN]

shopping_list = ["eggs", "milk", "bread", "butter"]

 List Slicing

List slicing is a technique in Python that enables us to extract specific elements or subsequences
from a list. It provides a concise and efficient way to work with lists by allowing us to access,
modify, and manipulate elements based on their indices. We can easily create new lists, extract
sublists, replace or delete elements, and perform various other operations with list slicing.

 Benefits of List Slicing in Python

List slicing offers several benefits, making it a valuable tool for Python developers. Some of the
key advantages include:

Concise and readable code

List slicing allows us to perform complex operations on lists using a compact and intuitive
syntax, resulting in more readable code.

Dr. Yusuf Perwej Page 28


Efficient data manipulation

With list slicing, we can efficiently extract, modify, and manipulate elements within a list,
reducing the need for extensive loops or iterations.

Flexibility and versatility

List slicing provides a flexible way to work with lists, enabling us to perform various operations,
such as accessing specific elements, creating sublists, reversing lists, and more.

Code reusability

By utilizing list slicing techniques, we can write reusable code snippets that can be applied to
different lists or scenarios, enhancing code modularity and maintainability.

 Basic List Slicing Syntax

The basic syntax for list slicing in Python is as follows:

new_list = original_list[start:end:step]

- `start`: The index at which the slicing should begin (inclusive).


- `end`: The index at which the slicing should end (exclusive).
- `step`: The increment value for selecting elements (optional).

 Accessing Specific Elements in a List

 Accessing a Single Element

To access a single element from a list, we can specify the index of the desired element within
square brackets.

Example:
fruits = ['apple', 'banana', 'cherry', 'date']
second_fruit = fruits[1]
print(second_fruit)

Output:
'banana'

Explanation
1. List Creation
o A list named fruits contains four elements: ‘apple,’ ‘banana,’ ‘cherry,’ and ‘date.’
2. Accessing a Single Element
o The code accesses the element at index 1 in the fruits list.
o In Python, list indices start from 0, so fruits[1] refer to the second element in the
list, ‘banana.’
o The value ‘banana’ is assigned to the variable second_fruit.
3. Printing the Result
o Finally, it prints the value of second_fruit, ‘banana.’

Dr. Yusuf Perwej Page 29


 Accessing Multiple Elements

We can use list slicing to access multiple elements from a list. We can extract a subsequence of
elements by specifying the start and end indices.

Example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


subsequence = numbers [2:6]
print(subsequence)

Output:
[3, 4, 5, 6]

Explanation
1. List of Numbers:
o A number list contains ten elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.
2. List Slicing to Create a Subsequence:
o The code uses list slicing to create a subsequence from the numbers list.
o numbers[2:6] selects elements starting from index 2 up to, but not including,
index 6.
o The subsequence includes elements at indices 2, 3, 4, and 5, which correspond to
the values 3, 4, 5, and 6 in the original list.
o The resulting subsequence is [3, 4, 5, 6] and assigned to the variable subsequence.
3. Printing the Result:
o Finally, it prints the value of the subsequence, which is [3, 4, 5, 6].

 Accessing Elements with Step Size

List slicing also allows us to select elements with a specific step size. We can skip elements
while specifying the step value while extracting a subsequence.

Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = numbers[1:10:2]
print(even_numbers)

Output:
[2, 4, 6, 8, 10]

Explanation
1. List Slicing with a Step to Create a Subsequence of Even Numbers
o The code uses list slicing with a step of 2 to create a subsequence of even
numbers from the numbers list.
o numbers[1:10:2] selects elements starting from index 1 up to, but not including,
index 10 with a step of 2.
o The selected elements include indices 1, 3, 5, 7, and 9, corresponding to the
values 2, 4, 6, 8, and 10 in the original list.
o The resulting subsequence is [2, 4, 6, 8, 10], and it is assigned to the variable
even_numbers.

Dr. Yusuf Perwej Page 30


 Negative Indexing in List Slicing

Python supports negative indexing, which allows us to access elements from the end of a list.
We can use negative indices in list slicing to extract elements from the reverse direction.

Example:
fruits = ['apple', 'banana', 'cherry', 'date']
last_two_fruits = fruits[-2:]
print(last_two_fruits)

Output:
['cherry', 'date']

Explanation
1. List Slicing with Negative Indexing to Extract the Last Two Fruits
o The code uses list slicing with negative indexing to extract the last two elements
from the list of fruits.
o fruits[-2:] starts from the element at index -2 (second-to-last element) and goes
until the end of the list.
o Negative indices in Python refer to positions counting from the end of the list,
with -1 being the last element, -2 being the second-to-last, and so on.
o The resulting subsequence is [‘cherry,’ ‘date’], assigned to the variable
last_two_fruits.

 Modifying Lists using Slicing

 Replacing Elements in a List

List slicing enables us to replace elements within a list by assigning new values to the selected
subsequence.

Example:
numbers = [1, 2, 3, 4, 5]
numbers[1:4] = [10, 20, 30]
print(numbers)

Output:
[1, 10, 20, 30, 5]

Explanation
Replacing Elements in a List using List Slicing:
 The code uses list slicing to select a subsequence of elements from index 1 to 4
(excluding index 4).
 The selected subsequence is [2, 3, 4] and replaced with the new values [10, 20, 30].
 After this operation, the modified numbers list becomes [1, 10, 20, 30, 5].

 Deleting Elements from a List

We can delete elements from a list using list slicing by assigning an empty list to the selected
subsequence.

Example:

Dr. Yusuf Perwej Page 31


numbers = [1, 2, 3, 4, 5]
numbers[1:4] = []
print(numbers)

Output:
[1, 5]

Explanation
Deleting Elements from a List using List Slicing:
 The code uses list slicing to select a subsequence of elements from index 1 to 4
(excluding index 4).
 The selected subsequence is [2, 3, 4] and replaced with an empty list [].
 This operation effectively deletes the elements [2, 3, 4] from the original numbers list.

 Inserting Elements into a List

List slicing also allows us to insert elements into a list at specific positions. We can insert new
elements by assigning a list of elements to an empty subsequence.

Example:
numbers = [1, 2, 3, 4, 5]
numbers[1:1] = [10, 20, 30]
print(numbers)

Output:
[1, 10, 20, 30, 2, 3, 4, 5]

Explanation
Inserting Elements into a List using List Slicing:
 The code uses list slicing to select an empty subsequence at index 1 (between the first
and second elements).
 The selected subsequence is empty ([]), and it is replaced with a new list [10, 20, 30].
 This operation effectively inserts the elements [10, 20, 30] at position 1 in the original
numbers list.

 Advanced List Slicing Techniques

 Skipping Elements using Extended Slices

In addition to the basic list slicing syntax, Python provides extended slices that allow us to skip
elements while extracting a subsequence. We can select elements regularly by specifying a step
value greater than 1.

Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
skipped_elements = numbers[::2]
print(skipped_elements)

Output:
[1, 3, 5, 7, 9]

Dr. Yusuf Perwej Page 32


 Reversing a List using Slicing

List slicing can reverse a list by specifying a negative step value. This technique allows us to
create a reversed copy of the original list.

Example:
numbers = [1, 2, 3, 4, 5]
reversed_numbers = numbers[::-1]
print(reversed_numbers)

Output:
[5, 4, 3, 2, 1]

 Creating Sublists using Slicing

We can create sublists from a list by using list slicing. We can extract a portion of the original
list by specifying the start and end indices.

Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sublist = numbers[2:8]
print(sublist)

Output:
[3, 4, 5, 6, 7, 8]

 Combining Multiple Slices

Python allows us to combine multiple slices to create complex sublists. Using the `+` operator,
we can concatenate different slices into a single list.

Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
combined_slices = numbers[1:4] + numbers[7:]
print(combined_slices)

Output:
[2, 3, 4, 8, 9, 10]

 List Slicing with Strings and Tuples

 Slicing Strings

List slicing techniques can also be applied to strings in Python. We can extract substrings from a
string using the same syntax as list slicing.

Example:
text = "Hello, World!"
substring = text[7:12]
print(substring)

Dr. Yusuf Perwej Page 33


Output:
"World"

 Slicing Tuples

Similarly, tuples can also be sliced using list slicing syntax. We can extract sub-tuples from a
tuple based on the specified indices.

Example:
coordinates = (10, 20, 30, 40, 50)
subtuple = coordinates[1:4]
print(subtuple)

Output:
(20, 30, 40)

 Get all the Items

Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[:])

Output:
[1, 2, 3, 4, 5]

Note:- If you simply use :, you will get all the elements of the list. This is similar to print(my_list).

 Get all the Items After a Specific Position

Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[2:])

Output:
[3, 4, 5]

If you want to get all the elements after a specific index, you can mention that index before : as
shown in example above.
In the above example, elements at index 2 and all the elements after index 2 are printed.

Note: Indexing starts from 0. Item on index 2 is also included.

 Get all the Items Before a Specific Position

Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[:2])

Outpu:
[1, 2]

This example lets you get all the elements before a specific index. Mention that index after :.

Dr. Yusuf Perwej Page 34


In the example, the items before index 2 are sliced. Item on index 2 is excluded.

 Get all the Items from One Position to Another Position

Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])

Output:
[3, 4]

If you want to get all the elements between two specific indices, you can mention them before
and after :.
In the above example, my_list[2:4] gives the elements between 2nd and the 4th positions. The
starting position (i.e. 2) is included and the ending position (i.e. 4) is excluded.

 Get the Items at Specified Intervals

Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[::2])

Output:
[1, 3, 5]

If you want to get elements at specified intervals, you can do it by using two :.
In the above example, the items at interval 2 starting from index 0 are sliced.
If you want the indexing to start from the last item, you can use negative sign -.

Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[::-2])

Output:
[5, 3, 1]

 Use of Tuple data type

Python tuples are a type of data structure that is very similar to lists. The main difference between
the two is that tuples are immutable, meaning they cannot be changed once they are created. A
tuple can have any number of items, which may be of different types, such as a string, integer,
float, list, etc. A Python tuple is a sequence of comma separated items, enclosed in parentheses ().
The items in a Python tuple need not be of same data type.

Example:
# Creating a Tuple
# with the use of string
Tuple1 = ('Gitm', 'For')
print(Tuple1)

Output:
'Gitm', 'For'

Dr. Yusuf Perwej Page 35


 Unpacking a Tuple

When we create a tuple, we normally assign values to it. This is called "packing" a tuple:

 Packing a tuple

Example:
fruits = ("apple", "banana", "cherry")

But, in Python, we are also allowed to extract the values back into variables. This is called
"unpacking":

 Unpacking a tuple

fruits = ("apple", "banana", "cherry")


(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)

Output:
apple
banana
cherry

Note: The number of variables must match the number of values in the tuple, if not, you must
use an asterisk to collect the remaining values as a list.

 Using Asterisk*

If the number of variables is less than the number of values, you can add an * to the variable
name and the values will be assigned to the variable as a list:

Assign the rest of the values as a list called "red":

Example:
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)

Output:
apple
banana
['cherry', 'strawberry', 'raspberry']

If the asterisk is added to another variable name than the last, Python will assign values to the
variable until the number of values left matches the number of variables left.

Add a list of values the "tropic" variable:

Dr. Yusuf Perwej Page 36


Example:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)

Output:
apple
['mango', 'papaya', 'pineapple']
cherry

 Nested Tuples

Tuples can hold other tuples within them, creating what we call ‘nested tuples’. This is useful
when you want to group related data together. Here’s an example:

Example:
nested_tuple = (('apple', 'banana'), ('cherry', 'date'))
print(nested_tuple)

Output:
(('apple', 'banana'), ('cherry', 'date'))

In this example, nested_tuple contains two tuples, each with two elements.

 Tuples as Dictionary Keys

Because of their immutability, tuples can be used as keys in Python dictionaries, unlike lists.
This is advantageous when you need a composite key, i.e., a key that is made up of multiple
parts.

Example:
fruit_colors = {( 'apple', 'banana'): 'yellow', ('cherry', 'date'): 'red'}
print(fruit_colors[('apple', 'banana')])

Output:
yellow

Here, we’ve used tuples as keys in our fruit_colors dictionary. When we print the value
associated with the key ('apple', 'banana'), we get ‘yellow’.

 Navigating Tuple Troubles

While working with Python tuples, you may encounter some common errors or obstacles.

 Attempting to Modify a Tuple

Dr. Yusuf Perwej Page 37


One of the most common errors when working with tuples is trying to modify them. Remember,
tuples are immutable. Let’s see what happens when we try to change a tuple:

Example:
ruit_tuple = ('apple', 'banana', 'cherry')
fruit_tuple[0] = 'orange'

Output:
TypeError: 'tuple' object does not support item assignment

The above code returns a TypeError because we’re trying to change a tuple, which is not
allowed in Python. If you need a collection of items that can be modified, consider using a list
instead.

 Unpacking a Tuple Incorrectly

Another common issue arises when trying to unpack more or fewer variables than the tuple
contains.

Example:
fruit_tuple = ('apple', 'banana', 'cherry')
fruit1, fruit2 = fruit_tuple

Output:
ValueError: too many values to unpack (expected 2)

In this case, Python throws a ValueError because we’re trying to unpack a three-item tuple into
only two variables. To solve this, ensure the number of variables matches the number of items in
the tuple.

 Delving into Python Immutability

Immutability is a fundamental concept in Python that directly impacts how we work with tuples.
But what does it really mean for a data structure to be immutable, and why is it so important?
In Python, an immutable object is an object whose state cannot be changed after it’s created. This
means that once you’ve defined an immutable object, such as a tuple, you can’t add, remove, or
change its elements. Let’s see this in action:

Example:
fruit_tuple = ('apple', 'banana', 'cherry')
fruit_tuple[0] = 'orange'

Output:
TypeError: 'tuple' object does not support item assignment

In the above code, Python throws a TypeError when we try to change an element in the tuple. This
is Python’s way of enforcing immutability.

 The Importance of Immutability

Dr. Yusuf Perwej Page 38


 Immutability is important for a couple of reasons. First, it provides a degree of safety.
When you define a tuple, you can be sure its data will remain constant throughout the
program, preventing accidental modifications.
 Second, immutability makes Python tuples hashable, meaning they can be used as
dictionary keys, unlike lists. This is a powerful feature when you need a composite key,
i.e., a key made up of multiple parts.

 Use of String data type

The string is a collection of characters. It is one of Python's most often-used data types . You can
create a Python string by enclosing a sequence of characters in single quotes (”) or double quotes
(“”).

Example:
my_string = 'Hello, Python!'
print(my_string)

Output:
'Hello, Python!'

In this example, we’ve created a string my_string that contains the text ‘Hello, Python!’. We
then print the string to the console, resulting in the output ‘Hello, Python!’.

 Reassigning Strings in Python

In the Python programming language, strings (sequences of characters) can have new values
assigned to them using the basic assignment operator (=). Once a string has been initially defined
and given a value, that string variable can later be reassigned to a new and different
value. Reassigning string variables is a fundamental part of Python.

Reassignment works for strings and other variable types in Python, like integers, floats, booleans,
lists, dictionaries, and more. So, strings are not unique in being able to be reassigned, but
Reassignment is still an important concept to understand for working with strings in Python
programs.

Example:
myString = "Gitm"
myString = "Gitm and Goel"
print(myString)

Output:
Gitm and Goel

Note:- The string object doesn't support item assignment i.e., A string can only be replaced with
new string since its content cannot be partially replaced. Strings are immutable in Python.

Example:
str = "HELLO"
str[0] = "h"
print(str)

Dr. Yusuf Perwej Page 39


Output:
Traceback (most recent call last):
File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment

However, in example 1, the string str can be assigned completely to a new content as specified
in the following example

Example:
str = "HELLO"
print(str)
str = "hello"
print(str)

Output:
HELLO
hello

 String Operators

Operator Description
It is known as concatenation operator used to join the strings given either side of the
+
operator.
It is known as repetition operator. It concatenates the multiple copies of the same
*
string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
It is known as range slice operator. It is used to access the characters from the
[:]
specified range.
It is known as membership operator. It returns if a particular sub-string is present in
in
the specified string.
It is also a membership operator and does the exact reverse of in. It returns true if a
not in
particular substring is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need
r/R to print the actual meaning of escape characters such as "C://python". To define any
string as a raw string, the character r or R is followed by the string.
It is used to perform string formatting. It makes use of the format specifiers used in C
% programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.

Example:
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.

Dr. Yusuf Perwej Page 40


print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello

Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

 Python String Formatting

 Escape Sequence

Suppose we need to write the text as - They said, "Hello what's going on?"- the given statement
can be written in single quotes or double quotes but it will raise the SyntaxError as it contains
both single and double-quotes.

Example:

str = "They said, "Hello what's going on?""


print(str)

Output:

SyntaxError: invalid syntax

We can use the triple quotes to accomplish this problem but Python provides the escape
sequence.

The backslash (/) symbol denotes the escape sequence. The backslash can be followed by a
special character and it interpreted differently. The single quotes inside the string must be
escaped. We can apply the same as in the double quotes.

Example:
# using triple quotes
print('''''They said, "What's there?"''')

# escaping single quotes


print('They said, "What\'s going on?"')

# escaping double quotes


print("They said, \"What's going on?\"")

Output:

They said, "What's there?"


They said, "What's going on?"
They said, "What's going on?"

Dr. Yusuf Perwej Page 41


 Use of List data type
Lists in Python are mutable, allowing for easy modification through various methods. It’s a
versatile tool that allows you to store multiple items in a single variable.

 Converting a String to a List of Characters

Below we have code implementation and explanation of converting string data type to list data
type in Python.

Example:
string = 'hello'
char_list = list(string)
print(char_list)

Output:
['h', 'e', 'l', 'l', 'o']

Explanation
This code creates a string called string and converts it to a list of characters called char_list using
the built-in list() function. Each character in the string becomes a separate element in the list.

 Converting a Tuple to a List

Below we have code implementation and explanation of converting tuple data type to list data
type in Python.

Example:
tuple = (1, 2, 3, 4)
list1 = list(tuple)
print(list1)

Output:
[1, 2, 3, 4]

Explanation
This code creates a tuple called a tuple and converts it to a list called a list using the built-in list()
function. The elements in the tuple become elements in the list in the same order.

 Converting a Range to a List

Below we have code implementation and explanation of converting range object to list data type
in Python.

Example:
range_obj = range(1, 5)
list = list(range_obj)
print(list)

Output:
Dr. Yusuf Perwej Page 42
[1, 2, 3, 4]

Explanation
This code creates a range object called range_obj that represents the numbers 1 through 4 and
converts it to a list called list using the built-in list() function. The range object is converted into
a list with the same values.

 Converting a Dictionary to a List

Below we have code implementation and an explanation of converting a dictionary to a list data
type in Python.

Example:
dict = {'apple': 1, 'banana': 2, 'orange': 3}
key_list = list(dict.keys())
value_list = list(dict.values())
print(key_list)
print(value_list)

Output:
['apple', 'banana', 'orange']
[1, 2, 3]

Explanation
This code creates a dictionary called dict and converts its keys and values to separate lists called
key_list and value_list using the built-in list() function. The keys and values become separate
elements in the lists. Overall, type conversion into lists is a useful feature in Python that allows
you to convert data from different types into a list, making it easier to manipulate and work
within your code.

 Use of Dictionary data type

Dictionaries in Python are a capable and adaptable data structure that permits you to store and
manipulate collections of key-value pairs.

A dictionary comes in handy when we have to store or manipulate data and create complex data
mappings with its use as a nested data structure with efficient operations. It is helpful in mapping
a key to its value that can be accessed in constant time which gives it an edge over the list in
terms of searching or retrieving the value for a particular key.

Dr. Yusuf Perwej Page 43


Dictionaries can be created in Python using several ways with the most often used being opening
and closing curly braces. We can store values in the dictionary upon its creation where the key
and value are separated using a colon (‘:’) with the values being separated by a comma (‘,’).

 Syntax 1 for creating a python dictionary

languages = {
"key1": value1,
"key2": ,value2
"key3": value3,
"key4": value4
}

Another valid way to create a dictionary is by using the dict() method where the built-in
constructor creates a dictionary upon interpreting it.

 Syntax 2 for creating a python dictionary

dict = dict(key1='value1', key2='value2')

Dictionary Comprehension is another but slightly complex way to create a dictionary where an
iterator is performed inside to store the key-value pairs in a similar technique to how it is
implemented with List Comprehension.

 Syntax 3 for creating a python dictionary

dict = {key: value for key, value in (('key1', 'value1'), ('key2', 'value2'))}

Now that we have a clear idea on how to create a dictionary, we will move forward to study how
manipulations can be made on a Python Dictionary.

 Check if a key exist in Dictionary

We can determine if a given key is present in the dictionary or not by using the in operator.

 key in Dict

Python program to use in operator to check if a key is available in the dictionary.

Example:
Dict = {
"name":"Goel",
"blog":"howtodoinpython",
"age":39
}

if "name" in Dict:
print("name is present")
else:
print("name is not present")

Output:

Dr. Yusuf Perwej Page 44


name is present

 key not in Dict

Python program to use in operator to check if a key is not present in the dictionary.

Example:
Dict = {
"name":"Goel",
"blog":"howtodoinpython",
"age":39
}

if "country" not in Dict:


print("country is not present")
else:
print("country is present")

Output:
country is not present

 fromkeys()

The fromkeys() method returns a dictionary with the specified keys and value.

Example:
keys = ('key1', 'key2', 'key3')
value = 0

Dict = dict.fromkeys(keys, value)

print(Dict)

Output:
{'key1': 0, 'key2': 0, 'key3': 0}

 get()

The get() method returns the value of the specified key.

Example:
Dict = {"name":"Goel", "blog":"howtodoinpython"}

print(Dict.get("name"))

Output:
Goel

 items()

The items() method returns a list containing a tuple for each key value pair.

Dr. Yusuf Perwej Page 45


Example:
Dict = {"name":"Goel", "blog":"howtodoinpython"}

print(Dict.items())

for i in Dict.items():
print(i)

Output:
dict_items([('name', 'Goel'), ('blog', 'howtodoinpython')])
('name', 'Goel')
('blog', 'howtodoinpython')

 keys()

The keys() method returns a list containing the dictionary’s keys.

Example:
Dict = {"name":"Goel", "blog":"howtodoinpython"}

print(Dict.keys())

for i in Dict.keys():
print(i)

Output:
dict_keys(['name', 'blog'])

name
blog

 setdefault()

The setdefault() method returns the value of the specified key. If the specified key does not exist
in the dictionary, the method inserts the key, with the specified value.

Example:
Dict = {"name":"Goel", "blog":"howtodoinpython"}

Dict.setdefault("age", "39")
print(Dict)

Output:
{'name': 'Lokesh', 'blog': 'howtodoinjava', 'age': '39'}

 Multidict

A multidict is like a special kind of dictionary in Python that allows us to have more than one
value for the same key. In a regular dictionary, each key can have only one value, but with a
multidict, a key can be associated with multiple values.

Dr. Yusuf Perwej Page 46


Imagine we have a list of your favorite colors. In a regular dictionary, you can only associate one
color with each day:

colors = {'Monday': 'Blue', 'Tuesday': 'Red', 'Wednesday': 'Green'}

But with a multidict, you can have multiple colors for the same day: from multidict import
MultiDict

colors = MultiDict()
colors.add('Monday', 'Blue')
colors.add('Monday', 'Yellow')
colors.add('Tuesday', 'Red')
colors.add('Wednesday', 'Green')

Here, ‘Monday’ has two colors associated with it (‘Blue’ and ‘Yellow’). It’s like having a bag
where you can put many items with the same tag.

 Manipulations Building blocks of python programs

There are more than Six Building blocks of Python. A few of them are listed below.

1. Variables : Variables are the storage spaces to store texts or numbers. In python you don’t
need to assign data types to a variable. Python dynamically assign data type to every variable on
the basis of value assigned to it. e.g. num= 1 will assign integer type to variable who’s name is
num.

2. Identifiers : Identifiers are the names given to variables or functions etc. There are some rules
that python follow for identifiers.

 a. User-defined identifiers can consist of letters, digits, underscores, and the


dollar-sign $
 b. Must start with a non-digit
 c. Identifiers are case sensitive (count and Count are different variables)
 d. Reserved words (keywords) cannot be used as identifiers
 e. an identifier can be any length

3. Data Types : It refer to what type of data a variable will store. Python dynamically assign data
types to its variable on the basis of values that is assigned to it. Following are some data types
that Python supports.

 a. Boolean - has two possible values, True or False


 b. integer (int) types - for storage of integer values
 c. floating (float) point types - for storage of decimal numbers
 d. string (str) type used to store strings in memory.
 e. list - are also refered to as arrays that can contain mixed datatypes.
 f. object - user defined types.
 g. Dictionaries

4. Comments : Comments in Python start with the hash character, # , and extend to the end of the
physical line. A comment may appear at the start of a line or following white space or code, but
not within a string literal. A hash character within a string literal is just a hash character.

Dr. Yusuf Perwej Page 47


5. Operators : Operators are the symbols that that perform specific mathematical, relational or
logical operation on operands. There are different types of operators like arithmetic operators
which perform arithmetic operations like addition, Subtraction, Multiplication etc. Assignment
operator that assign value to a variable etc.

6. Expressions : Expressions are nothing but values, except they can have operations like
addition or subtraction. e.g.

a=7

b=8

c=a+b

here a+b is an expression

7. Statements : These are the instructions that a python interpreter can execute. e.g. a=2*4 is a
Statement

8. Functions : A function is a set of statements that take inputs, do some specific computation
and produces output. There are mainly two types of functions in Python, User Define and Built
in functions. 'print' is a good example of built in function where as one can create User define
function by using 'def' keyword.

9. Classes : Python is an object oriented programming language. Almost everything in Python is


an object, with its properties and methods. A Class is like an object constructor, or a "blueprint"
for creating objects. e.g

class MyClass:

x=5

 Programming using string in-built functions

 Basic String Functions

 lower()

The lower() string function returns a given string into a new string where all characters are in
lowercase. This specific function simply ignores symbols and numbers and, thus, has nothing to
do with them.

Syntax: “string.lower()” is the syntax of the lower string function.

Example:
string = “Internshala is Working to Equip Students with Relevant Skills and Practical Exposure”
print(string.lower())

Output:
internshala is working to equip students with relevant skills and practical exposure

Dr. Yusuf Perwej Page 48


 Upper()

The upper() string function returns a given string into a new string where all characters are in the
uppercase. This specific function simply ignores symbols and numbers and, thus, has nothing to
do with them. “string.upper()” is the syntax of the upper string function.

Example:
string = “Internshala is Working to Equip Students with Relevant Skills and Practical Exposure”
print(string.upper())

Output:

INTERNSHALA IS WORKING TO EQUIP STUDENTS WITH RELEVANT SKILLS AND


PRACTICAL EXPOSURE

 capitalize()

The capitalize() string function returns a given string into a new string where only the first
character is in the uppercase and all the remaining characters are in the lowercase.

Syntax: “string.capitalize()” is the syntax of capitalize string function.

Example:
string = “i am learning the PYTHON Programming Language”
print(string.capitalize())

Output:
I am learning python programming language.

 title()

The title() string function returns a given string into a new string where the first character of
each word is in the uppercase, and the remaining characters are in the lowercase.

Syntax: “string.title()” is the syntax of the title string function.

Example:
string = “i am learning PYTHON Programming Language”
print(string.title())

Output:
I Am Learning Python Programming Language

 casefold()

]Similar to the lower() string function, the casefold() function returns a given string into a new
string where all characters are in lowercase. However, the casefold() function is stronger and is
used to perform a case-insensitive comparison.

Syntax: “string.casefold()” is the syntax of the casefold string function.

Dr. Yusuf Perwej Page 49


Example:
string = ““I Am learning PYTHON PROGRAMMING LANGUAGE”
print(string.casefold())

Output:
i am learning python programming language

 swapcase()

The swapcase() string function returns an uppercase lettered string into a new string with all
letters in the lowercase and vice-versa.

Syntax: “string.swapcase()” is the syntax of the swapcase string function.

Example:
string = “I AM LEARNING PYTHON PROGRAMMING LANGUAGE”
print(string.swapcase())

Output:
i am learning python programming language

Example:
string - “i am learning python programming language”
print(string.swapcase())

Output:
I AM LEARNING PYTHON PROGRAMMING LANGUAGE

 format()

The Python string format function is used to format the string for console printing.

Syntax: “string.format()” is the syntax of the format string function.

Example:
string = “I have {an : .2f} Candies!”
print (string.format() (an = 4)

Output:
I have 4 Candies!

 Find and Replace String Functions

 encode()

The encode() function is used to encode the string using a specified encoding scheme.

Syntax: “string.encode()” is the syntax of encode string function.

Example:

#Variable Declaration

Dr. Yusuf Perwej Page 50


string = “HELLO”
encode = str.encode()
#Displaying Result
print(“Old value”,str)
print(“Encoded value”,encode)

Output:
old vale HELLO

 Encoded value b ‘HELLO’

 find()

The find() function is used to find the index of a given substring in a string.
Syntax: “string.find()” is the syntax of the find string function.

Example:

string = “Python is a fun programming language”


#check the index of ‘fun’
print(string.find(‘fun’))

Output:
12

 replace()

The replace() function is used to return a string where a specified value is replaced with another
specified value.

Syntax: “string.replace()” is the syntax of replace string function.

Example:
string = “bat ball”
#replacing ‘ba’ with ‘ro’
replaced_string - string.replace(‘ba’ , ‘ro’)
print(replaced_string)

Output:
rot roll

Let’s check out some more find and replace string functions in python with examples:

Function Description Syntax


The rfind() function is used to search a given string for a specified
rfind() string.rfind()
value and return the last position of where it was found.
The index() function returns the first position of the first occurrence
index() string.index()
of a substring in a string.
The rindex() function returns the highest index of the substring
rindex() string.rindex()
inside a string.

Dr. Yusuf Perwej Page 51


 Checks String Functions

The following table specifies checks string functions:

Function Description Syntax


The startswith() function returns “True” when the string
startswith() string.startswith()
starts with the given substring, otherwise it returns ‘False.’
The endswith() function returns “True” when the string ends
endswith() string.endswith()
with the given substring, otherwise it returns ‘False.’
The isdigit() function returns ‘True’ when all characters in a
isdigit() string.isdigit()
given string are digits, otherwise it returns ‘False.’
The isalnum() function returns ‘True’ when all characters in
isalnum() a given string are alphanumeric, otherwise it returns string.isalnum()
‘False.’
The isalpha() function returns ‘True’ when all characters in
isalpha() string.isalpha()
a given string are alphabets, otherwise it returns ‘False.’
The isidentifier() function returns ‘True’ when a given
isidentifier() string.isidentifier()
string is valid, otherwise it returns ‘False.’
The isdecimal() function returns ‘True’ when all characters
isdecimal() string.isdecimal()
in a given string are decimals, otherwise it returns ‘False.’
The isnumeric() function returns ‘True’ when all characters
isnumeric() string.isnumeric()
in a given string are numeric, otherwise it returns ‘False.’
The islower() function returns ‘True’ when all cased
islower() characters in a given string are lowercase and there is at string.islower()
least one cased character, otherwise it returns ‘False.’
The isprintable() function returns ‘True’ when all characters
isprintable() string.isprintable()
in a given string are printable, otherwise it returns ‘False.’
The isupper() function returns ‘True’ when all cased
isupper() characters in a given string are uppercase, otherwise it string.isupper()
returns ‘False.’
The isspace() function returns ‘True’ when there are all
isspace() whitespace characters in a given string, otherwise it returns string.isspace()
‘False.’
The istitle() function returns ‘True’ when a given string is
istitle() string.istitle()
title cased and not empty, otherwise it returns ‘False.’

 Padding and Cleaning String Functions

Following table specifies the various padding and cleaning string functions:

Function Description Syntax


The center() function is used to pad a given string with the specified
center() string.center()
character.
The strip() function is used to remove both leading and trailing
strip() string.strip()
characters from a given string.
The rstrip() function is used to remove the trailing characters from a
rstrip() string.rstrip()
given string.

Dr. Yusuf Perwej Page 52


The lstrip() function is used to remove the leading characters from a
lstrip() string.lstrip()
given string.
The ljust() function is used to align a given string to the left using a
ljust() string.ljust()
specified width.
The rjust() function is used to align a given string to the right using a
rjust() string.rjust()
specified width.
The zfill() function is used to return a string’s copy with ‘0’
zfill() string.zfill()
characters padded to the left side of the string.

 Python Split and Join String Functions

The following table specifies the various split and join string functions:
Function Description Syntax
join () The join() function is used to return a concatenated string. string.join()
The partition() function is used to split the string on the first
partition() string.partition()
occurrence of the separator.
The rpartition() function is used to split the string into three
rpartition() string.rpartition()
parts.
The split() function is used to split a string using a specified
split() string.split()
separator.
The rsplit() function is used to split a string from the right
rsplit() string.rsplit()
using a specified separator.
The splitlines() function is used to split the lines at line
splitlines() string.splitlines()
boundaries.

 Miscellaneous String Functions

The following table specifies miscellaneous string functions:

Function Description Syntax


The format_map() function is used to format specified
format_map() string.format_map()
values in a given string using a dictionary.
The count() function is used to count the number of
count() string.count()
occurrences of a substring in a given string.
The translate() function is used to change the given string.translate()
translate()
string using translation mappings.

 Programming using list in-built functions

 Types of List Functions

Python programming language has a different type of python list methods that helps user
manipulate data. Following are the various list functions.

 Sort List Method

The sort () list is an in-built method in Python. You can sort data in ascending order using this
method. You can also change it from descending to ascending by changing its criteria.
Syntax – sort()
Dr. Yusuf Perwej Page 53
Example:
age = [25, 19, 88, 43, 24, 52]
age.sort()
print(age)

Output:
[19,24,25,43,52,88]

 Type List Function

This function is mainly used for debugging purposes. When used, it will show you the class type
of the object.
Syntax – type()

Example:
marks = [“rahul”, 85, “manav”, 91, “shubam”, 79, “aditya”, 88 ]
marks
Output:
[‘rahul’, 85, ‘manav’, 91, ‘shubam’, 79, ‘aditya’, 88 ]
Input:
type(marks)

Output:
list

 Append List Method

The append() list method adds content toward the end of the elements you select. This is a very
useful and quick method of adding content to elements.
Syntax – append()

Example:
places = [‘Jaipur’, ‘Udaipur’, ‘Kota’]
places.append(‘Ajmer’)
print(places)

Output:
[‘Jaipur,’ ‘Udaipur,’ ‘Kota,’ ‘Ajmer’]

 Extend List Method

The extend list method – extend() can add multiple elements/numbers provided to the method at
the end of the current list. This method, unlike append, can add a multitude of elements.
Syntax – extend()

Example:
a = [1, 2, 3, 4]
a.extend([5,6])
a

Output:

Dr. Yusuf Perwej Page 54


[1, 2, 3, 4, 5, 6]

 Index List Method

This method returns you to the first time when the given value appeared in the data. This is
useful while analyzing and sorting data.
Syntax – index()

Example:
date = [‘12’, ‘13’, ‘14’, ‘15’]
day = [‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’]
date.index(14)

Output:
2

Now we can use this data to find the corresponding data related to this value, In this case, the
day.
Input:
print(day[3])
Output:
Tuesday

 Max List Function

The max list function – max() will give you the maximum value among the input values. This is
quite useful in data analysis.
Syntax – max()

Example:

#finding out the max-age


age = [25, 19, 88, 43, 24, 52]
age_max = max(age)
print(age_max)

Output:
88

 Min List Function

The min list function – min() will give you the minimum value among the input values. This is,
again, quite useful in data analysis and sorting.
Syntax – min()

Example:
#finding out the min age
age = [25, 19, 88, 43, 24, 52]
age_min = min(age)
print(age_min)

Output:

Dr. Yusuf Perwej Page 55


19

 Len List Function

The len list function- len() is used to find the number of elements in a list. Let us look at the
example below to understand this better –
Syntax – len()

Example:
January = [ 19, 27, 30 ]
February = [ 12, 21 ]
print(‘january length is ‘, len(january))
print(‘february length is ‘, len(february))

Output:
January length is 3
February length is 3

 Python List Function

The Python List function – list() creates a list of objects. It is an in-built and widely used
function. Let us look at the example below to understand it better-
Syntax – list()

Example:
day = [‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’]
print(list(day))

Output:
[‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’]

 Compare or Cmp List Function

The Compare or Cmp list function – Cmp() compares two values against one another and returns
the difference, whether it is positive, negative, or zero. It is a very useful tool in data sorting and
analysis.
Syntax – Cmp ()

Example:
Rahul = [85]
Manav = [91]
print(cmp(rahul, manav)
print(cmp(rahul, rahul)
print(cmp(manav, rahul)

Output:
-6
0
6

This result showed us that Manav achieved more marks than Rahul and by what value. This
function is especially useful while dealing with big numbers.

Dr. Yusuf Perwej Page 56


 Filter List Function

The filter list function – filter() filters items through a function and returns the iterator after
testing if the items were accepted or rejected. This helps us filter desirable elements from
undesirable elements by using the function as a filter.
Syntax – filter ()

Example:
def filter_age(age):
if (age>30):
return True
Else:
return False
people_age = [25, 19, 88, 43, 24, 52]
filtered_age = filter(filter_age, people_age)
print(list(filtered_age))

Output:
[43,52,88]

as you may have noticed, this function is very useful especially while data sorting as it helps to
separate unwanted elements from the entire dataset.

 Let’s quickly summarize what we have learned so far


Description Syntax
Function
Sort List The sort () list is an in-built method in Python. You can sort data
sort ()
Function in ascending order using this method.
Type List
When used, it will show you the class type of the object. type()
Function
Append List The append() list method adds content toward the end of the
append()
Function elements you select.
Extend List The extend list method – can add multiple elements/numbers
extend()
Function provided to the method at the end of the current list.
Index List This method returns you to the first time when the value appeared
index()
Function in the data.
Max List The max list function will give you the maximum value among
max()
Function the input values.
Min List The min list function will give you the minimum value among the
min()
Function input values.
Len List The len list function is used to find the number of elements in a
Len()
Function list.
Python List
The Python List function creates a list of objects list()
function
The Compare or Cmp list function compares two values against
Compare or Cmp
one another and returns the difference, whether it is positive, Cmp()
List Function
negative, or zero.
Filter List The filter list function filters items through a function and returns
filter()
Function the iterator after testing if the items were accepted or rejected.

Dr. Yusuf Perwej Page 57


 Programming using dictionary in-built functions

 Built-in Dictionary Functions

A function is a method that can be used on a construct to yield a value. Additionally, the
construct is unaltered. A few of the Python methods can be combined with a Python dictionary.

The built-in Python dictionary methods are listed below, along with a brief description.

 len()

The dictionary's length is returned via the len() function in Python. The string is lengthened by
one for each key-value pair.
Example:
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
len(dict)

Output:
4
 any()

Like how it does with lists and tuples, the any() method returns True indeed if one dictionary key
does have a Boolean expression that evaluates to True.

Example:
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
any({'':'','':'','3':''})

Output:
True

 all()

Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True
Boolean value.

Example:
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
all({1:'',2:'','':''})

Output:
False

 sorted()

Like it does with lists and tuples, the sorted() method returns an ordered series of the dictionary's
keys. The ascending sorting has no effect on the original Python dictionary.

Example:
dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}
sorted(dict)

Dr. Yusuf Perwej Page 58


Output:
[ 1, 5, 7, 8]

 Built-in Dictionary methods

The built-in python dictionary methods along with the description and code are given below.

 clear()

It is mainly used to delete all the items of the dictionary.

Example:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# clear() method
dict.clear()
print(dict)

Output:
{}

 copy()

It returns a shallow copy of the dictionary which is created.

Example:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# copy() method
dict_demo = dict.copy()
print(dict_demo)

Output:
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

 pop()

It mainly eliminates the element using the defined key.

Example:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# pop() method
dict_demo = dict.copy()
x = dict_demo.pop(1)
print(x)

Output:
{2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

 popitem()

Dr. Yusuf Perwej Page 59


removes the most recent key-value pair entered

Example:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# popitem() method
dict_demo.popitem()
print(dict_demo)

Output:
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}

 keys()

It returns all the keys of the dictionary.

Example:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# keys() method
print(dict_demo.keys())

Output:
dict_keys([1, 2, 3, 4, 5])

 items()

It returns all the key-value pairs as a tuple.

Example:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# items() method
print(dict_demo.items())

Output:
dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])

 get()

It is used to get the value specified for the passed key.

Example:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# get() method
print(dict_demo.get(3))

Output:
Facebook

Dr. Yusuf Perwej Page 60


 update()

It mainly updates all the dictionary by adding the key-value pair of dict2 to this dictionary.

Example:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# update() method
dict_demo.update({3: "TCS"})
print(dict_demo)

Output:
{1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}

 values()

It returns all the values of the dictionary with respect to given input.

Example:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# values() method
print(dict_demo.values())

Output:
dict_values(['Hcl', 'WIPRO', 'TCS'])

 Python includes the following dictionary functions –

Sr.No Function with Description


cmp(dict1, dict2)
1
Compares elements of both dict.
len(dict)
2 Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
str(dict)
3
Produces a printable string representation of a dictionary
type(variable)
4 Returns the type of the passed variable. If passed variable is dictionary, then it
would return a dictionary type.

 Python includes following dictionary methods –

Sr.No Methods with Description


dict.clear()
1
Removes all elements of dictionary dict
dict.copy()
2
Returns a shallow copy of dictionary dict

Dr. Yusuf Perwej Page 61


Sr.No Methods with Description
dict.fromkeys()
3
Create a new dictionary with keys from seq and values set to value.
dict.get(key, default=None)
4
For key key, returns value or default if key not in dictionary
dict.has_key(key)
5
Returns true if key in dictionary dict, false otherwise
dict.items()
6
Returns a list of dict's (key, value) tuple pairs
dict.keys()
7
Returns list of dictionary dict's keys
dict.setdefault(key, default=None)
8
Similar to get(), but will set dict[key]=default if key is not already in dict
dict.update(dict2)
9
Adds dictionary dict2's key-values pairs to dict
dict.values()
10
Returns list of dictionary dict's values

 Python Functions

Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the
same code again and again for different inputs, we can do the function calls to reuse code contained
in it over and over again. Functions provide better modularity for your application and a high
degree of code reusing.

 Types of Python Functions

Python provides the following types of functions

 Built-in functions
 Functions defined in built-in modules
 User-defined functions

 Python's standard library includes number of built-in functions. Some of Python's built-in
functions are print(), int(), len(), sum(), etc. These functions are always available, as they
are loaded into computer's memory as soon as you start Python interpreter.

 The standard library also bundles a number of modules. Each module defines a group of
functions. These functions are not readily available. You need to import them into the
memory from their respective modules.

 In addition to the built-in functions and functions in the built-in modules, you can also
create your own functions. These functions are called user-defined functions.

 Defining a Python Function

Dr. Yusuf Perwej Page 62


You can define custom functions to provide the required functionality. Here are simple rules to
define a function in Python.

 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
 The first statement of a function can be an optional statement; the documentation string
of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.

 Syntax to Define a Python Function

A function is a reusable block of programming statements designed to perform a certain task. To


define a function, Python provides the def keyword. The following is the syntax of defining a
function.

Syntax:

def function_name(parameters):
"""docstring"""
statement1
statement2
...
...
return [expr]

 The keyword def is followed by a suitable identifier as the name of the function and
parentheses. One or more parameters may be optionally mentioned inside parentheses.

 The : symbol after parentheses starts an indented block.

 The first statement in the function body can be a string, which is called the docstring. It explains
the functionality of the function/class. The docstring is not mandatory.

 The function body contains one or more statements that perform some actions. It can also use
pass keyword.

Dr. Yusuf Perwej Page 63


 Optionally, the last statement in the function block is the return statement. It sends an execution
control back to calling the environment. If an expression is added in front of return, its value is
also returned to the calling code.

 Creating a Function in Python

We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require. By the following example, we can understand
how to write a function in Python. In this way we can create Python function definition by using
def keyword.

Example:
# A simple Python function
def fun():
print("Welcome to Goel")

 Calling a Function in Python

After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function. Below is the example
for calling def function Python.

Example:
# A simple Python function
def fun():
print("Welcome to Goel")

# Driver code to call a function


fun()

Output:
Welcome to Goel

 Python Function with Parameters


If you have experience in C/C++ or Java then you must be thinking about the return type of the
function and data type of arguments. That is possible in Python as well (specifically for Python
3.5 and above).

 Python Function Syntax with Parameters

def function_name(parameter: data_type) -> return_type:


"""Docstring"""
# body of the function
return expression

The following example uses arguments and parameters that you will learn later in this article so
you can come back to it again if not understood.

Example:
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2

Dr. Yusuf Perwej Page 64


return num3

# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")

Output:
The addition of 5 and 15 results 20.

Note: The following examples are defined using syntax 1, try to convert them in syntax 2 for
practice.

Example:
# some more functions
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r=3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))

Output:
False True

 Parameterized Function

The function parameters can have an annotation to specify the type of the parameter using
parameter:type syntax. For example, the following annotates the parameter type string.
However, you can pass any type of value to the goel() function.

Example: Parameterized Function


def goel(name:str):
print ('Hello ', name)

goel('Anjali')
goel(123)

Output:
Hello Anjali
Hello 123

 Python Function Arguments

Dr. Yusuf Perwej Page 65


Arguments are the values passed inside the parenthesis of the function. A function can have any
number of arguments separated by a comma.

In this example, we will create a simple function in Python to check whether the number passed
as an argument to the function is even or odd.

Example:
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)

Output:
even
odd

 Types of Python Function Arguments

Python supports various types of arguments that can be passed at the time of the function call. In
Python, we have the following function argument types in Python:

 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)

 Default Arguments

A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustrates Default arguments to write
functions in Python.

Example:
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only


# argument)
myFun(10)

Output:

Dr. Yusuf Perwej Page 66


x: 10
y: 50

Like C++ default arguments, any number of arguments in a function can have a default value.
But once we have a default argument, all the arguments to its right must also have default
values.

 Keyword Arguments

The idea is to allow the caller to specify the argument name with values so that the caller does
not need to remember the order of parameters.

Example:
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='Goel', lastname='Gitm')
student(lastname='Gitm', firstname='Goel')

Output:
Goel Gitm
Goel Gitm

 Positional Arguments

We used the Position argument during the function call so that the first argument (or value) is
assigned to name and the second argument (or value) is assigned to age. By changing the
position, or if you forget the order of the positions, the values can be used in the wrong places, as
shown in the Case-2 example below, where 27 is assigned to the name and Suraj is assigned to
the age.

Example:
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)

# You will get correct output because


# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")

Output:
Case-1:
Hi, I am Suraj

Dr. Yusuf Perwej Page 67


My age is 27
Case-2:
Hi, I am 27
My age is Suraj

 Arbitrary Keyword Arguments

In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:

 *args in Python (Non-Keyword Arguments)


 **kwargs in Python (Keyword Arguments)

Example 1: Variable length non-keywords argument


# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'GoelforGitm')

Output:
Hello
Welcome
to
GoelforGitm

Example 2: Variable length keyword arguments


# Python program to illustrate
# *kwargs for variable number of keyword arguments

def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

# Driver code
myFun(first='Goel', mid='for', last='Gitm')
Output:
first == Goel
mid == for
last == Gitm

 Docstring

The first string after the function is called the Document string or Docstring in short. This is used
to describe the functionality of the function. The use of docstring in functions is optional but it is
considered a good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)

Dr. Yusuf Perwej Page 68


Example: Adding Docstring to the function
# A simple Python function to check
# whether x is even or odd

def evenOdd(x):
"""Function to check if the number is even or odd"""

if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


print(evenOdd.__doc__)

Output:
Function to check if the number is even or odd

 Python Function within Functions

A function that is defined inside another function is known as the inner function or nested
function. Nested functions can access variables of the enclosing scope. Inner functions are used
so that they can be protected from everything happening outside the function.

Example:
# Python program to
# demonstrate accessing of
# variables of nested functions

def f1():
s = 'I love GoelforGitm '

def f2():
print(s)

f2()

# Driver's code
f1()

Output:
I love GoelforGitm

 Anonymous Functions in Python

In Python, an anonymous function means that a function is without a name. As we already know
the def keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions.

Dr. Yusuf Perwej Page 69


Example:
# Python code to illustrate the cube of a number
# using lambda function
def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))
print(cube_v2(7))

Output:
343
343

 Recursive Functions in Python

Recursion in Python refers to when a function calls itself. There are many instances when you
have to build a recursive function to solve Mathematical and Recursive Problems.

Using a recursive function should be done with caution, as a recursive function can become like a
non-terminating loop. It is better to check your exit statement while creating a recursive function.

Example:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))

Output
24

Here we have created a recursive function to calculate the factorial of the number. You can see
the end statement for this function is when n is equal to 0.

 Return Statement in Python Function

The function return statement is used to exit from a function and go back to the function caller
and return the specified value or data item to the caller. The syntax for the return statement is:
return [expression_list]

The return statement can consist of a variable, an expression, or a constant which is returned at
the end of the function execution. If none of the above is present with the return statement a
None object is returned.

Example: Python Function Return Statement


def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

Dr. Yusuf Perwej Page 70


print(square_value(2))
print(square_value(-4))

Output:
4
16

 Pass by Reference and Pass by Value

One important thing to note is, in Python every variable name is a reference. When we pass a
variable to a function Python, a new reference to the object is created. Parameter passing in
Python is the same as reference passing in Java.

Example:
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output:
[20, 11, 12, 13, 14, 15]

When we pass a reference and change the received reference to something else, the connection
between the passed and received parameters is broken. For example, consider the below program
as follows:

Example:
def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]

# Driver Code (Note that lst is not modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output:
[10, 11, 12, 13, 14, 15]
Another example demonstrates that the reference link is broken if we assign a new value (inside
the function).

Dr. Yusuf Perwej Page 71


Example:
def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = 20

# Driver Code (Note that x is not modified


# after function call.
x = 10
myFun(x)
print(x)

Output:
10

Exemple:
def swap(x, y):
temp = x
x=y
y = temp

# Driver code
x=2
y=3
swap(x, y)
print(x)
print(y)

Output:
2
3

 The Various Types of Functions in Python

In Python, functions can be categorized into several types based on their purpose and behavior.
Here are the main types of functions:

 Built-in Functions:
These are functions that are pre-defined in Python and are available for use without requiring
any additional imports. Examples include len(), print(), type(), range(), and sum().

 User-Defined Functions:
These are functions created by users to perform specific tasks. They are defined using the def
keyword. User-defined functions promote code reusability and modularity.

 Anonymous Functions (Lambda Functions):


Lambda functions are small, unnamed functions defined using the lambda keyword. They are
often used for short, simple operations that can be expressed in a single line of code.

 Recursive Functions:

Dr. Yusuf Perwej Page 72


Recursive functions are functions that call themselves as part of their execution. They are
particularly useful for solving problems that can be divided into smaller instances of the same
problem.

 Higher-Order Functions:
Higher-order functions take one or more functions as arguments and/or return a function as their
result. They enable functional programming paradigms and can make code more concise and
readable.

 Pure Functions:
Pure functions are functions that always produce the same output for the same input and have no
side effects. They don't modify external variables or objects, which makes them easier to reason
about and test.

 Impure Functions:
Impure functions have side effects, such as modifying external state or variables. They can lead
to unexpected behavior and make code harder to understand and test.

 Generator Functions:
Generator functions use the yield keyword to yield values one at a time, allowing for memory-
efficient iteration over large datasets. They are used to create iterators using the concept of lazy
evaluation.

 Decorator Functions:
Decorators are functions that modify the behavior of other functions. They allow you to add
functionality to a function without modifying its code directly. Decorators are often used for
tasks like logging, authentication, and memoization.

 Static Methods:
Static methods are defined inside a class but are not bound to the instance. They can be called on
the class itself and are often used for utility functions that don't require access to instance-
specific data.

 Class Methods:
Class methods are defined inside a class and are bound to the class rather than an instance. They
can access and modify class-level attributes and are often used for factory methods or alternate
constructors.

 Creating a Function in Python

Example:
# function creation
def fun():
print("Welcome to upGrad!")

# call a function
fun()

 Calling Python Functions

Example:

Dr. Yusuf Perwej Page 73


# function creation
def fun():
print("Welcome to upGrad!")

# call a function
fun()

 Python Function with Parameters

Example:
def greet(name):
return f"Hello, {name}!"

person = "Alice"
message = greet(person)
print(message) # Output: Hello, Alice!

 Python Function Arguments

Example:
def add_numbers(x, y):
return x + y

result = add_numbers(5, 3)
print(result) # Output: 8

 The Different Types of Python Function Arguments Default argument

Example:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"

message1 = greet("Alice")
message2 = greet("Bob", "Hi")

print(message1) # Output: Hello, Alice!


print(message2) # Output: Hi, Bob!

 Keyword arguments (named arguments)

Example:
def display_info(name, age, city):
return f"Name: {name}, Age: {age}, City: {city}"

info = display_info(name="Alice", city="New York", age=30)


print(info) # Output: Name: Alice, Age: 30, City: New York

 Positional arguments

Example:
def add_numbers(x, y):
return x + y

Dr. Yusuf Perwej Page 74


result = add_numbers(5, 3)
print(result) # Output: 8

 Arbitrary arguments

Example:
def display_names(*names):
for name in names:
print(name)

display_names("Alice", "Bob", "Charlie")

 Pass by Reference vs. Pass by Value

Example:
def myFun(p):
p[0] = 300
last = [100, 110, 120, 130, 140, 150]
myFun(last)
print(last)

 Python Function within Functions

Example:
def outer_function(x):
def inner_function(y):
return y ** 2

result = inner_function(x)
return result

input_number = 3
output = outer_function(input_number)
print("Result:", output) # Output: Result: 9

 Anonymous Functions in Python

Example:
numbers = [1, 2, 3, 4, 5]

# Using lambda in sorting


sorted_numbers = sorted(numbers, key=lambda x: x % 2) # Sort by odd/even

# Using lambda in mapping


squared_numbers = list(map(lambda x: x ** 2, numbers))

# Using lambda in filtering


even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(sorted_numbers) # Output: [2, 4, 1, 3, 5]

Dr. Yusuf Perwej Page 75


print(squared_numbers) # Output: [1, 4, 9, 16, 25]
print(even_numbers) # Output: [2, 4]

 Return Statement in Python Function

Example:
def add_numbers(x, y):
result = x + y
return result

sum_result = add_numbers(3, 5)
print("Sum:", sum_result) # Output: Sum: 8

 Advantages of Python Functions

1. Modularity:
Python functions advocate a modular design. Modularity implies that a complex system, in this
case, a program, is divided into separate modules or functions. Each function deals with a
specific sub-task, allowing for greater clarity.
This design not only makes it easier for developers to understand and navigate through the
codebase but also encourages collaborative work. Different developers can work on different
functions simultaneously, without intruding on each other's code.

2. Breakdown Complexity:
Functions are excellent tools to disintegrate a complex operation into more digestible sub-tasks.
By compartmentalizing code into functions, it becomes simpler to track, debug, and understand
the logic.
Each function stands alone, ensuring that the flow of data and logic is continuous and transparent
within that segment. This reduces cognitive overload, making troubleshooting and optimization
efforts more focused.

3. Reusability:
One of the most celebrated features of functions is reusability. A function is like a pre-packaged
unit of code ready to perform its defined task whenever called upon.
This means you can craft a well-optimized function once and then deploy it across various parts
of your application, or even across different projects.

4. Maintainability:
A direct offspring of modularity and reusability is the maintainability of the code. When code is
structured into specific functions, updating a feature or fixing an issue becomes much more
straightforward.
Developers can zero in on the exact function that needs alteration, making changes without
disturbing the larger machinery of the software. This modular approach reduces the risk of
introducing new bugs when making updates.

5. Flexibility:
Functions in Python, especially when they're parameterized, offer a high degree of flexibility.
Parameterized functions accept input values when they're called, allowing developers to mold a
generic solution to suit diverse scenarios.
This means that a single function can handle a wide range of situations, reducing the need for
creating multiple, similar functions.

Dr. Yusuf Perwej Page 76


6. Namespace Isolation:
Python functions provide a sanctuary for local variables. When a variable is defined within a
function, it remains local to that function, invisible to the outside world.
This ensures there's no unintended interference between the internal variables of the function and
external variables, offering a robust mechanism to prevent accidental data overlaps and
manipulations.

 The Scope and Lifetime of Variables

Example:
global_variable = "I am global"

def my_function():
local_variable = "I am local"
print(global_variable)
print(local_variable)

my_function()

print(global_variable)
# print(local_variable) # This would raise an error because local_variable is not accessible here.

 Python Capability inside Another Capability

Example:
def outer_function(x):
def inner_function(y):
return x + y

return inner_function

add_five = outer_function(5)
result = add_five(3) # This is equivalent to calling inner_function(3)
print(result) # Output: 8

 Lambda Functions

Python Lambda Functions are anonymous functions means that the function is without a name.
As we already know the def keyword is used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function in Python.

Python Lambda Function Syntax

Syntax: lambda arguments : expression

 This function can have any number of arguments but only one expression, which is
evaluated and returned.
 One is free to use lambda functions wherever function objects are required.
 You need to keep in your knowledge that lambda functions are syntactically restricted to
a single expression.
 It has various uses in particular fields of programming, besides other types of expressions
in functions.

Dr. Yusuf Perwej Page 77


Example:
calc = lambda num: "Even number" if num % 2 == 0 else "Odd number"

print(calc(20))

Output:
Even number

 Python lambda properties

 This function can have any number of arguments but only one expression, which is
evaluated and returned.
 One is free to use lambda functions wherever function objects are required.
 You need to keep in your knowledge that lambda functions are syntactically restricted to
a single expression.
 It has various uses in particular fields of programming, besides other types of expressions
in functions.

Example 1: Program to demonstrate return type of Python lambda keyword


string = 'GoelsforGitms'

# lambda returns a function object


print(lambda string: string)

Output
<function <lambda> at 0x14b8d29e01f0>

Explanation: In this above example, the lambda is not being called by the print function, but
simply returning the function object and the memory location where it is stored. So, to make the
print to print the string first, we need to call the lambda so that the string will get pass the print.

Example 2: Invoking lambda return value to perform various operations

Here we have passed various types of arguments into the different lambda functions and printed
the result generated from the lambda function calls.

filter_nums = lambda s: ''.join([ch for ch in s if not ch.isdigit()])


print("filter_nums():", filter_nums("Gitms101"))

do_exclaim = lambda s: s + '!'


print("do_exclaim():", do_exclaim("I am tired"))

find_sum = lambda n: sum([int(x) for x in str(n)])


print("find_sum():", find_sum(101))

Output:
filter_nums(): Gitms
do_exclaim(): I am tired!
find_sum(): 2

Dr. Yusuf Perwej Page 78


Example 3: Difference between lambda and normal function call
The main difference between lambda function and other functions defined using def keyword is
that, we cannot use multiple statements inside a lambda function and allowed statements are also
very limited inside lambda statements. Using lambda functions to do complex operations may
affect the readability of the code.

def cube(y):
print(f"Finding cube of number:{y}")
return y * y * y
lambda_cube = lambda num: num ** 3

# invoking simple function


print("invoking function defined with def keyword:")
print(cube(30))
# invoking lambda function
print("invoking lambda function:", lambda_cube(30))

Output:
invoking function defined with def keyword:
Finding cube of number:30
27000
invoking lambda function: 27000

Example 4: The lambda function gets more helpful when used inside a function.
We can use lambda function inside map(), filter(), sorted() and many other functions. Here, we
have demonstrated how to use lambda function inside some of the most common Python
functions.

l = ["1", "2", "9", "0", "-1", "-2"]


# sort list[str] numerically using sorted()
# and custom sorting key using lambda
print("Sorted numerically:",
sorted(l, key=lambda x: int(x)))

# filter positive even numbers


# using filter() and lambda function
print("Filtered positive even numbers:",
list(filter(lambda x: not (int(x) % 2 == 0 and int(x) > 0), l)))

# added 10 to each item after type and


# casting to int, then convert items to string again
print("Operation on each item using lambda and map()",
list(map(lambda x: str(int(x) + 10), l)))

Output
Sorted numerically: ['-2', '-1', '0', '1', '2', '9']
Filtered positive even numbers: ['1', '9', '0', '-1', '-2']
Operation on each item using lambda and map() ['11', '12', '19', '10', '9', '8']

 using mylist:

Dr. Yusuf Perwej Page 79


In this example, we define a lambda function that takes an argument x and adds 10 to it. We then
use the map() function to apply the lambda function to each element in the list my_list. Finally,
we convert the result to a list and print it.
Here’s another example that uses a lambda function to filter out even numbers from a list:

Example:
# Example list
my_list = [1, 2, 3, 4, 5]

# Use lambda to filter out even numbers from the list


new_list = list(filter(lambda x: x % 2 != 0, my_list))

# Print the new list


print(new_list)

Output
[1, 3, 5]

 Python Lambda Function Example

In the example, we defined a lambda function(upper) to convert a string to its upper case using
upper().

This code defines a lambda function named upper that takes a string as its argument and
converts it to uppercase using the upper() method. It then applies this lambda function to the

Example:
string ‘GoelsforGitms’ and prints the result
str1 = ' GoelsforGitms '

upper = lambda string: string.upper()


print(upper(str1))

Output:
GOELSFORGITMS

 Use of Lambda Function in Python

Let’s see some of the practical uses of the Python lambda function.

Condition Checking Using Python lambda function

Here, the ‘format_numric’ calls the lambda function, and the num is passed as a parameter to
perform operations.

Example:
format_numeric = lambda num: f"{num:e}" if isinstance(num, int) else f"{num:,.2f}"

print("Int formatting:", format_numeric(1000000))


print("float formatting:", format_numeric(999999.789541235))

Output:

Dr. Yusuf Perwej Page 80


Int formatting: 1.000000e+06
float formatting: 999,999.79

 Difference Between Lambda functions and def defined function

The code defines a cube function using both the ‘def' keyword and a lambda function. It
calculates the cube of a given number (5 in this case) using both approaches and prints the
results. The output is 125 for both the ‘def' and lambda functions, demonstrating that they
achieve the same cube calculation.

Example:
def cube(y):
return y*y*y

lambda_cube = lambda y: y*y*y


print("Using function defined with `def` keyword, cube:", cube(5))
print("Using lambda function, cube:", lambda_cube(5))

Output:
Using function defined with `def` keyword, cube: 125
Using lambda function, cube: 125

As we can see in the above example, both the cube() function and lambda_cube() function
behave the same and as intended. Let’s analyze the above example a bit more:

With lambda function Without lambda function


Supports single-line sometimes statements that Supports any number of lines inside a
return some value. function block
Good for performing short operations/data Good for any cases that require multiple
manipulations. lines of code.
Using the lambda function can sometime We can use comments and function
reduce the readability of code. descriptions for easy readability.

 Python Lambda Function with List Comprehension

On each iteration inside the list comprehension, we are creating a new lambda function with a
default argument of x (where x is the current item in the iteration). Later, inside the for loop, we
are calling the same function object having the default argument using item() and get the desired
value. Thus, is_even_list stores the list of lambda function objects.

Example:
is_even_list = [lambda arg=x: arg * 10 for x in range(1, 5)]
for item in is_even_list:
print(item())
Output:
10
20
30
40
 Python Lambda Function with if-else

Dr. Yusuf Perwej Page 81


Here we are using the Max lambda function to find the maximum of two integers.

Example:
Max = lambda a, b : a if(a > b) else b
print(Max(1, 2))
Output:
2

 Python Lambda with Multiple Statements

Lambda functions do not allow multiple statements, however, we can create two lambda
functions and then call the other lambda function as a parameter to the first function. Let’s try to
find the second maximum element using lambda.

The code defines a list of sublists called ‘List'. It uses lambda functions to sort each sublist and
find the second-largest element in each sublist. The result is a list of second-largest elements,
which is then printed. The output displays the second-largest element from each sublist in the
original list.

Example:
List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]]

sortList = lambda x: (sorted(i) for i in x)


secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]
res = secondLargest(List, sortList)
print(res)
Output:
[3, 16, 9]

 Lambda functions can be used along with built-in functions like filter(), map() and
reduce().

 Using lambda() Function with filter()

The filter() function in Python takes in a function and a list as arguments. This offers an elegant
way to filter out all the elements of a sequence “sequence”, for which the function returns True.
Here is a small program that returns the odd numbers from an input list:

 Filter out all odd numbers using filter() and lambda function

Here, lambda x: (x % 2 != 0) returns True or False if x is not even. Since filter() only keeps
elements where it produces True, thus it removes all odd numbers that generated False.

Example:
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

final_list = list(filter(lambda x: (x % 2 != 0), li))


print(final_list)
Output:
[5, 7, 97, 77, 23, 73, 61]
 Filter all people having age more than 18, using lambda and filter() function

Dr. Yusuf Perwej Page 82


The code filters a list of ages and extracts the ages of adults (ages greater than 18) using a
lambda function and the ‘filter' function. It then prints the list of adult ages. The output displays
the ages of individuals who are 18 years or older.

Example:
ages = [13, 90, 17, 59, 21, 60, 5]
adults = list(filter(lambda age: age > 18, ages))

print(adults)
Output:
[90, 59, 21, 60]

 Using lambda() Function with map()

The map() function in Python takes in a function and a list as an argument. The function is called
with a lambda function and a list and a new list is returned which contains all the lambda-
modified items returned by that function for each item.

 Multiply all elements of a list by 2 using lambda and map() function

The code doubles each element in a list using a lambda function and the ‘map' function. It then
prints the new list with the doubled elements. The output displays each element from the original
list, multiplied by 2.

Example:
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

final_list = list(map(lambda x: x*2, li))


print(final_list)
Output:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

 Transform all elements of a list to upper case using lambda and map() function

The code converts a list of animal names to uppercase using a lambda function and the ‘map'
function. It then prints the list with the animal names in uppercase. The output displays the
animal names in all uppercase letters.

Example:
animals = ['dog', 'cat', 'parrot', 'rabbit']
uppered_animals = list(map(lambda animal: animal.upper(), animals))

print(uppered_animals)
Output:
['DOG', 'CAT', 'PARROT', 'RABBIT']

 Using lambda() Function with reduce()

The reduce() function in Python takes in a function and a list as an argument. The function is
called with a lambda function and an iterable and a new reduced result is returned. This performs
a repetitive operation over the pairs of the iterable. The reduce() function belongs to the
functools module.

Dr. Yusuf Perwej Page 83


 A sum of all elements in a list using lambda and reduce() function

The code calculates the sum of elements in a list using the ‘reduce' function from the
‘functools' module. It imports ‘reduce', defines a list, applies a lambda function that adds two
elements at a time, and prints the sum of all elements in the list. The output displays the
computed sum.
from functools import reduce

Example:
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print(sum)
Output:
193

Here the results of the previous two elements are added to the next element and this goes on till
the end of the list like (((((5+8)+10)+20)+50)+100).

 Find the maximum element in a list using lambda and reduce() function

The code uses the ‘functools' module to find the maximum element in a list (‘lis') by employing
the ‘reduce' function and a lambda function. It then prints the maximum element, which is 6 in
this case.

import functools

Example:
lis = [1, 3, 5, 6, 2, ]
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))

Output:
The maximum element of the list is : 6

Dr. Yusuf Perwej Page 84

You might also like