0% found this document useful (0 votes)
9 views100 pages

Introduction to Python Programming

The document provides an introduction to Python programming, covering its structure, features, and execution modes. It discusses key concepts such as branching, looping, functions, and the use of the Python interpreter in both interactive and script modes. Additionally, it outlines the syntax for various control structures and the importance of functions in code reusability.

Uploaded by

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

Introduction to Python Programming

The document provides an introduction to Python programming, covering its structure, features, and execution modes. It discusses key concepts such as branching, looping, functions, and the use of the Python interpreter in both interactive and script modes. Additionally, it outlines the syntax for various control structures and the importance of functions in code reusability.

Uploaded by

subamtech
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

INTRODUCTION TO PYTHON

SUBJECT CODE:U23ADTC01
SUBJECT NAME: Programming In Python

Presented by
[Link],AP/CSE
Sri Manakula Vinayagar Engineering College
14/11/2025 DEPARTMENTOFBME 1
UNIT 1
Topics in UNIT 1:
• Structure of Python Program
• Mechanism of module Execution
• Branching and looping
• Problem Solving using branches loops
• Functions
• Lambda functions
• List and Mutability
• Problem solving using Lists and Functions

14/11/2025 DEPARTMENTOFBME 2
GENERAL
• It was created by Guido van Rossum during
1985- 1990.
• Python got its name from “Monty Python’s
flying circus”. Python was released in the
year 2000.
• General purpose interpreted,
interactive ,object oriented, high level
programming.

14/11/2025 DEPARTMENTOFBME 3
ABOUT PYTHON
Python is interpreted: Python is processed at
runtime by the interpreter. You do not need to
compile your program before executing it.
Python is Interactive: You can actually sit at a
Python prompt and interact with the interpreter
directly to write your programs.
Python is Object-Oriented: Python supports
Object-Oriented style or technique of
programming that encapsulates code within
objects.
14/11/2025 DEPARTMENTOFBME 4
PYTHON FEATURES
Easy-to-learn: Python is clearly defined and easily readable. The structure
of the program is very simple. It uses few keywords.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
Portable: Python can run on a wide variety of hardware platforms and has
the same interface on all platforms.
Interpreted: Python is processed at runtime by the interpreter. So, there is
no need to compile a program before executing it. You can simply run the
program.
Extensible: Programmers can embed python within their C,C+
+,JavaScript, ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source
code, and edit it.
High Level Language: When writing programs, programmers concentrate
on solutions of the current problem, no need to worry about the low level
details.
Scalable: Python provides a better structure and support for large
programs than shell scripting.

14/11/2025 DEPARTMENTOFBME 5
MODES OF PYTHON INTERPRETER
• Python Interpreter is a program
that reads and executes Python
code.
• It uses 2 modes of Execution.
[Link] mode
[Link] mode

14/11/2025 DEPARTMENTOFBME 6
Interactive mode
• Interactive Mode, as the name suggests, allows us to interact with OS.
• When we type Python statement, interpreter displays the result(s)
immediately.
Advantages:
• Python, in interactive mode, is good enough to learn, experiment or explore.
• Working in interactive mode is convenient for beginners and for testing small
pieces of code.
Drawback:
• We cannot save the statements and have to retype all the statements once
again to re-run them. In interactive mode, you type Python programs and
the interpreter displays the result:
• >>> 1 + 1
• 2

14/11/2025 DEPARTMENTOFBME 7
Interactive mode
• The chevron, >>>, is the prompt the
interpreter uses to indicate that it is ready
for you to enter code. If you type 1 + 1, the
interpreter replies 2.
• >>> print ('Hello, World!') Hello, World!

14/11/2025 DEPARTMENTOFBME 8
Script mode
• In script mode, we type python program in a
file and then use interpreter to execute the
content of the file.
• Scripts can be saved to disk for future use.
• Python scripts have the extension .py,
meaning that the filename ends [Link]
• Save the code with [Link] and run the
interpreter in script mode to execute the script

14/11/2025 DEPARTMENTOFBME 9
Integrated Development Learning
Environment(IDLE)
• Its a graphical user interface which is completely
written in Python.
• It is bundled with the default implementation of the
python language and also comes with optional
part of the Python packaging.
Features of IDLE:
• Multi-window text editor with syntax highlighting.
• Auto completion with smart indentation.
• Python shell to display output with syntax
highlighting.
14/11/2025 DEPARTMENTOFBME 10
STRUCTURE OF PYTHON PROGRAM
• Comments: Comments are used to explain the purpose of the code or to make notes for other
programmers. They start with a ‘#’ symbol and are ignored by the interpreter.
• Import Statements: Import statements are used to import modules or libraries into the
program. These modules contain predefined functions that can be used to accomplish tasks.
• Variables: Variables are used to store data in memory for later use. In Python, variables do not
need to be declared with a specific type.
• Data Types: Python supports several built-in data types including integers, floats, strings,
Booleans, and lists.
• Operators: Operators are used to perform operations on variables and data. Python supports
arithmetic, comparison, and logical operators.
• Control Structures: Control structures are used to control the flow of a program. Python
supports if-else statements, for loops, and while loops.
• Functions: Functions are used to group a set of related statements together and give them a
name. They can be reused throughout a program.
• Classes: Classes are used to define objects that have specific attributes and methods. They
are used to create more complex data structures and encapsulate code.
• Exceptions: Exceptions are used to handle errors that may occur during the execution of a
program.

14/11/2025 DEPARTMENTOFBME 11
MODULE EXECUTION
• It uses 2 modes of Execution.
[Link] mode
[Link] mode

14/11/2025 DEPARTMENTOFBME 12
BRANCHING in PYTHON
• Refers to the control structures that allow your program to make
decisions and execute different blocks of code based on certain
conditions.
• The sequence of the control flow may differ from normal logical code.
Decision structures evaluate multiple expressions which produce
TRUE or FALSE as outcome. It is needed to determine which action to
take and which statements to execute if outcome is TRUE or FALSE
otherwise.
• Python programming language provides following types of decision
making statements.
• Types of Conditional statements
• if statements (conditional)
• if-else statements (alternative)
• if-elif-else (chained conditional)
• Nested Conditional

14/11/2025 DEPARTMENTOFBME 13
if statements (conditional)
• conditional (if) is used to test a condition, if
the condition is true the statements inside
if will be executed.
• Syntax:
if(condition 1):
statement 1

14/11/2025 DEPARTMENTOFBME 14
Conditional if: Flow chart

14/11/2025 DEPARTMENTOFBME 15
Alternative (if-else)

• In the alternative the condition must be true or false.


• In this else statement can be combined with if statement.
• The else statement contains the block of code that
executes when the condition is false.
• If the condition is true statements inside the if get
executed otherwise else part gets executed. The
alternatives are called branches, because they are
branches in the flow of execution.
• Syntax:
If(condition 1):
statement 1
else:
statement 2
14/11/2025 DEPARTMENTOFBME 16
Alternative if-else: Flow chart

14/11/2025 DEPARTMENTOFBME 17
Examples
1. odd or even number
2. positive or negative number
3. leap year or not

14/11/2025 DEPARTMENTOFBME 18
Chained conditionals (if-elif-else)
• The elif is short for else if.
• This is used to check more than one
condition.
• If the condition1 is False, it checks the
condition2 of the elif block. If all the conditions
are False, then the else part is executed.
• Among the several if...elif...else part, only one
part is executed according to the condition. The
if block can have only one else block. But it can
have multiple elif [Link] way to express a
computation like that is a chained conditional.
14/11/2025 DEPARTMENTOFBME 19
Syntax:Chained condtional if
if(condition 1):
statement 1
elif(condition 2):
statement 2
elif(condition 3):
statement 3
else:
default statement
14/11/2025 DEPARTMENTOFBME 20
Chained if
• A user can decide among multiple options.
The if statements are executed from the
top down.
• As soon as one of the conditions
controlling the if is true, the statement
associated with that if is executed, and the
rest of the ladder is bypassed.
• If none of the conditions is true, then the
final else statement will be executed.

14/11/2025 DEPARTMENTOFBME 21
Syntax-chained-if
Syntax:
if (condition):
statement
elif (condition):
Statement
.
.
else:
statement
14/11/2025 DEPARTMENTOFBME 22
Flowchart-chained-if

14/11/2025 DEPARTMENTOFBME 23
Nested if
• A nested if is an if statement that is the
target of another if statement.
• Nested if statements means an if
statement inside another if statement.
• Python allows us to nest if statements
within if statements. i.e, we can place an if
statement inside another if statement.

14/11/2025 DEPARTMENTOFBME 24
Syntax-Nested-if

if (condition1):
# Executes when condition1 is true if
(condition2):
# Executes when condition2 is true # if Block
is end here
# if Block is end here

14/11/2025 DEPARTMENTOFBME 25
Flowchart-Nested-if

14/11/2025 DEPARTMENTOFBME 26
LOOPING in PYTHON
• Python supports basic loop structures
through iterative statements.
• Iterative statements are decision control
statements that are used to repeat the
execution of list of statements.
• Python language supports two types
iterative statements-while and for loop.

14/11/2025 DEPARTMENTOFBME 27
THE WHILE LOOP

Definition : The while loop in Python execute a


block of one or more statements as long the
given condition remains true.
When to use a while loop?
• A while loop is used when the user does not
know in advance that for how many times the
loop body will execute.
• Therefore, a while loop is important when we
do not know the exact number of iterations in
advance.

14/11/2025 DEPARTMENTOFBME 28
Syntax-while loop

while condition:
indented-statemnt-1
indented-statemnt-2
...
last-indented-statement

14/11/2025 DEPARTMENTOFBME 29
Flowchart-while loop

14/11/2025 DEPARTMENTOFBME 30
Explanation of the Syntax of while loop
• while is a reserved word.
• condition is a boolean expression that gives a True or False result
• a colon :
• A block of one or more indented statements represents the body of the while
loop. It means that, the set of statements that will be executed as long as
the given condition remains true. We also call the block of statements a
‘while clause’.
• Note: indented statements are included in loop body, and if a statement is
written with no indentation after last-indented-statement, this will not be
included in the body of loop.
• Intialization and Increment / decrement of loop control variable
• We must remember that we will intialize the loop control variable before the
while loop statement. Moreover, we must take care to change the value of a
loop control variable inside the blck of statements (loop body).
• The change of value means either incrementing the value or decrementing
the value in some way, so as the while loop will terminate at last. If we do
not perform some action in loop body, there is a chance that the loop will
becomes an infinite loop.

14/11/2025 DEPARTMENTOFBME 31
Working of the while loop statement in
Python
• First of all, the given condition is tested, if it is
true, the control will execute the while clause
that is body of loop.
• After executing the whole block, the condition
is tested again. If it is true, then the control
will execute the body of loop once again. This
process continues as long as the given
condition remains true. The loop is terminated
if the given condition becomes false.

14/11/2025 DEPARTMENTOFBME 32
for loop in Python
• A for loop in Python requires at least two variables to
work. The first is the iterateble object such as a list,
tuple or a string. And second is the variable to store
the successive values from the sequence in the loop.
• Python For Loop Syntax
for iter in sequence:
statements(iter)
• The “iter” represents the iterating variable. It gets
assigned with the successive values from the input
sequence.
• The “sequence” may refer to any of the following
Python objects such as a list, a tuple or a string.
14/11/2025 DEPARTMENTOFBME 33
Flowchart-for loop

14/11/2025 DEPARTMENTOFBME 34
FUNCTIONS
• Functions are generally the block of codes or
statements in a program that gives the user the
ability to reuse the same code which ultimately
saves the excessive use of memory, acts as a time
saver and more importantly, provides better
readability of the code.
• So basically, a function is a collection of
statements that perform some specific task and
return the result to the caller.
• A function can also perform some specific task
without returning anything. In Python,def keyword
is used to create functions.
14/11/2025 DEPARTMENTOFBME 35
Syntax-Function
def function_name(parameters):
statement(s)
return expression

14/11/2025 DEPARTMENTOFBME 36
Creating a Function
We can create a Python function using the
def keyword.
Example
def fun():
print("What a wonderful world")
fun()
Output:
What a wonderful world

14/11/2025 DEPARTMENTOFBME 37
Calling a Function
After creating a function we can call it by
using the name of the function followed by
parenthesis containing parameters of that
particular function.
Example
def fun():
print(“ALL is WELL")
fun()
Output:
ALL is WELL
14/11/2025 DEPARTMENTOFBME 38
The return statement
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.
Syntax: return [expression_list]
The return statement can consist of a variable,
an expression, or a constant which is returned
to the end of the function execution. If none of
the above is present with the return statement a
None object is returned.
14/11/2025 DEPARTMENTOFBME 39
Example-Return Statement
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(8))
print(square_value(10))
Output
64
100
14/11/2025 DEPARTMENTOFBME 40
Types of Functions in Python

• User – defined functions.


• Built – in functions.
• Lambda functions.
• Recursive functions.

14/11/2025 DEPARTMENTOFBME 41
TYPES OF FUNCTION ARGUMENTS

1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments.

14/11/2025 DEPARTMENTOFBME 42
Example: Python Function with arguments
In this example, we will create a simple function to check whether the
number passed as an argument to the function is even or odd.
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

evenOdd(28)
evenOdd(3)

OUTPUT:
even
odd

14/11/2025 DEPARTMENTOFBME 43
Lambda Function
• Lambda function is mostly used for creating
small and one-time anonymous function.
• Lambda functions are mainly used in
combination with the functions like filter(),
map() and reduce().
• Lambda function can take any number of
arguments and must return one value in the
form of an expression.

14/11/2025 DEPARTMENTOFBME 44
Syntax-lambda function
• SYNTAX: lambda [argument(s)] :expression

14/11/2025 DEPARTMENTOFBME 45
Lists and Mutability
 List is a sequence of values, which can be
of different types. The values in list are
called "elements" or ''items''
 Each elements in list is assigned a
number called "position" or "index"
 A list that contains no elements is called
an empty list. They are created with empty
brackets []
 A list within another list is nested list

14/11/2025 DEPARTMENTOFBME 46
Creating a list
 The simplest way to create a new list is to
enclose the elements in square brackets ([])
 10,20,30,40
 [100, "python" , 8.02]
 Example:
thislist = ["apple", "banana", "cherry"]
print(thislist)
 Output:['apple', 'banana', 'cherry']

14/11/2025 DEPARTMENTOFBME 47
List Items
 List items are ordered, changeable, and allow duplicate
values.
 List items are indexed, the first item has index [0], the second
item has index [1] etc.
 Ordered
 When we say that lists are ordered, it means that the items
have a defined order, and that order will not change.
 If you add new items to a list, the new items will be placed at
the end of the list.
 Changeable
 The list is changeable, meaning that we can change, add,
and remove items in a list after it has been created.
 Allow Duplicates
 Since lists are indexed, lists can have items with the same
value
14/11/2025 DEPARTMENTOFBME 48
Duplicates

 Example
 Lists allow duplicate values:
 thislist = ["apple", "banana", "cherry",
"apple", "cherry"]
 print(thislist)
 Output
 ['apple', 'banana', 'cherry', 'apple', 'cherry']
 mylist=[23,67,4,5]
 Print(mylist)
 [23,67,4,5]
14/11/2025 DEPARTMENTOFBME 49
List Length

 To determine how many items a list has, use the len()


function:
 Example
 Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
 Output
3
Mylist=[8,9,56,65,3,4]
Print(len(mylist))
6
14/11/2025 DEPARTMENTOFBME 50
List Items - Data Types

• List items can be of any data type:


• Example
• String, int and boolean data types:
• list1 = ["apple", "banana", "cherry"]
• list2 = [1, 5, 7, 9, 3]
• list3 = [True, False, False]

14/11/2025 DEPARTMENTOFBME 51
List Items - Data Types

A list can contain different data types:

Example:
A list with strings, integers and Boolean
values:

list1 = ["abc", 34, True, 40, "male"]

14/11/2025 DEPARTMENTOFBME 52
The list() Constructor
• It is also possible to use the list() constructor when
creating a new list.

• Example
• Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) note :the double
round-brackets
print(thislist)
• Output:
• ['apple', 'banana', 'cherry']
14/11/2025 DEPARTMENTOFBME 53
Access Items

• List items are indexed and you can access


them by referring to the index number:
• Example
• Print the second item of the list:
• thislist = ["apple", "banana", "cherry"]
• print(thislist[1])
• Output:
• banana

14/11/2025 DEPARTMENTOFBME 54
Negative Indexing

 Negative indexing means start from the end


 -1 refers to the last item, -2 refers to the
second last item etc.
 Example
 Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
 Output:
 cherry

14/11/2025 DEPARTMENTOFBME 55
Slicing a List

• When you want only a part of a Python list,


you can use the slicing operator [].
• >>> indices=['zero','one','two','three','four','five']
• >>> indices[2:4]
• Output
• [‘two’, ‘three’]
• This returns items from index 2 to index 4-1
(i.e., 3)

14/11/2025 DEPARTMENTOFBME 56
Range of Indexes

• You can specify a range of indexes by specifying where to


start and where to end the range.
• When specifying a range, the return value will be a new list
with the specified items.
• Example
• Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:5])
• #This will return the items from position 2 to 5.
• #Remember that the first item is position 0,
• #and note that the item in position 5 is NOT included
• Output:
• 14/11/2025
['cherry', 'orange', 'kiwi'] DEPARTMENTOFBME 57
Range of Indexes
• Example
• This example returns the items from the beginning to, but
NOT including, "kiwi":
• thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
• print(thislist[:4])
• Note:
• #This will return the items from index 0 to index 4.
• #Remember that index 0 is the first item, and index 4 is
the fifth item
• #Remember that the item in index 4 is NOT included
• Output:
• 14/11/2025
['apple', 'banana', 'cherry', 'orange']
DEPARTMENTOFBME 58
Range of Indexes

• Example:
• thislist = ["apple", "banana", "cherry", "orange",
"kiwi", "melon", "mango"]
• print(thislist[2:])
• #This will return the items from index 2 to the end.
• #Remember that index 0 is the first item, and index
2 is the third
• Output:
• ['cherry', 'orange', 'kiwi', 'melon', 'mango']
14/11/2025 DEPARTMENTOFBME 59
Range of Negative Indexes
• Specify negative indexes if you want to start the search from
the end of the list:
• Example
• This example returns the items from "orange" (-4) to, but NOT
including "mango" (-1):
• thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
• print(thislist[-4:-1])
• Note:
• #Negative indexing means starting from the end of the list.
• #This example returns the items from index -4 (included) to
index -1 (excluded)
• #Remember that the last item has the index -1,
14/11/2025 DEPARTMENTOFBME 60
• Output:['orange', 'kiwi', 'melon']
Check if Item Exists
• To determine if a specified item is present in
a list use the in keyword:
• Example
• Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
• Output:
• Yes, 'apple' is in the fruits list
14/11/2025 DEPARTMENTOFBME 61
Change Item Value
• To change the value of a specific item, refer
to the index number:
• Example
• Change the second item:
• thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
• Output:
• ['apple', 'blackcurrant', 'cherry']

14/11/2025 DEPARTMENTOFBME 62
Change a Range of Item Values
• To change the value of items within a specific range,
define a list with the new values, and refer to the range of
index numbers where you want to insert the new values:
• Example
• Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":
• thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"mango"]
• thislist[1:3] = ["blackcurrant", "watermelon"]
• print(thislist)
• Output:
• ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi',
'mango']
14/11/2025 DEPARTMENTOFBME 63
Change a Range of Item Values

• If you insert more items than you replace, the


new items will be inserted where you specified,
and the remaining items will move accordingly:
• Example
• Change the second value by replacing it with
two new values:
• thislist = ["apple", "banana", "cherry"]
• thislist[1:2] = ["blackcurrant", "watermelon"]
• print(thislist)
• Output:
• ['apple', 'blackcurrant', 'watermelon', 'cherry']
14/11/2025 DEPARTMENTOFBME 64
Change a Range of Item Values
• If you insert less items than you replace, the new
items will be inserted where you specified, and the
remaining items will move accordingly:
• Example
• Change the second and third value by replacing it
with one value:
• thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
• Output:
• ['apple', 'watermelon']
14/11/2025 DEPARTMENTOFBME 65
Python list Methods

14/11/2025 DEPARTMENTOFBME 66
Insert Items
• To insert a new list item, without replacing any of the
existing values, we can use the insert() method.
• The insert() method inserts an item at the specified
index:
• Example
Insert "watermelon" as the third item:
thislist = ["apple", "banana", "cherry"]
[Link](2, "watermelon")
print(thislist)
• Output:
• ['apple', 'banana', 'watermelon', 'cherry']
14/11/2025 DEPARTMENTOFBME 67
Append Items

• To add an item to the end of the list, use the


append() method:
• Example
• Using the append() method to append an
item:
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
• Output:
• ['apple', 'banana', 'cherry', 'orange']
14/11/2025 DEPARTMENTOFBME 68
Extend List
• To append elements from another list to the current
list, use the extend() method.
• Example
• Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
[Link](tropical)
print(thislist)
• Output:
• ['apple', 'banana', 'cherry', 'mango', 'pineapple',
'papaya']
14/11/2025 DEPARTMENTOFBME 69
Add Any Iteratable

• The extend() method does not have to append


lists, you can add any iterable object (tuples, sets,
dictionaries etc.).
• Example
• Add elements of a tuple to a list:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
[Link](thistuple)
print(thislist)
• Output:
• ['apple', 'banana', 'cherry', 'kiwi', 'orange']
14/11/2025 DEPARTMENTOFBME 70
Remove Specified Item

• The remove() method removes the


specified item.
• Example
• Remove "banana":
thislist = ["apple", "banana", "cherry"]
[Link]("banana")
print(thislist)
• Output:
• ['apple', 'cherry']

14/11/2025 DEPARTMENTOFBME 71
Remove Specified Index

• The pop() method removes the specified


index.
• Example
• Remove the second item:
thislist = ["apple", "banana", "cherry"]
[Link](1)
print(thislist)
• Output:
• ['apple', 'cherry']

14/11/2025 DEPARTMENTOFBME 72
Remove Specified Index

• if you do not specify the index, the pop()


method removes the last item.
• Example
• Remove the last item:
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
• Output:
• ['apple', 'banana']
14/11/2025 DEPARTMENTOFBME 73
Remove Specified Index
• The del keyword also removes the specified
index:
• Example
• Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
• Output:
• ['banana', 'cherry']
14/11/2025 DEPARTMENTOFBME 74
Remove Specified Index
• The del keyword can also delete the list completely.

• Example
• Delete the entire list:
• thislist = ["apple", "banana", "cherry"]
• del thislist
• print(thislist) note: #this will cause an error because you have
succsesfully deleted "thislist".
• Output:
• Traceback (most recent call last):
• File "demo_list_del2.py", line 3, in <module>
• #this will cause an error because you have succsesfully deleted
"thislist".
• NameError: name 'thislist' is not defined
14/11/2025 DEPARTMENTOFBME 75
Clear the List
• The clear() method empties the list.

• The list still remains, but it has no content.

• Example
• Clear the list content:
• thislist = ["apple", "banana", "cherry"]
• [Link]()
• print(thislist)
• Output:
• []
14/11/2025 DEPARTMENTOFBME 76
Reverse
Reverses the order of the elements in the list, this places the final elements
at the beginning, and the initial elements at the end.

x = [1, 2, 'h', 3, 'h']


[Link]()
print(x)
• Output:
['h', 3, 'h', 2, 1]

14/11/2025 DEPARTMENTOFBME 77
sort
By default, this method sorts the elements of the list from smallest to largest, this behavior
can be modified using the parameter reverse = True

x = [3, 2, 1, 4]
[Link]()
print(x)
• Output:
[1, 2, 3, 4]

y = ['R', 'C', 'Python', 'Java', 'R']


[Link](reverse=True)
print(y)
• Output:
['R', 'R', 'Python', 'Java', 'C']
14/11/2025 DEPARTMENTOFBME 78
Immutable operations
These operations allow us to work with lists without altering or modifying their previous definition.

• sorted
• This method sorts the elements of a list from
smallest to largest, this is very similar to the
sort method, but this behavior can be modified
using the parameter reverse = True.
x = [5, 2, 9, 0]
print(sorted(x))
print(x)
• Output:
[0, 2, 5, 9]
14/11/2025 DEPARTMENTOFBME 79
Immutable operations
• +
• This operation allows us to concatenate or join two
different lists in a new list.
x = [1, 2, 3]
y = [4, 5, 6]
print(x + y)
print(x)
print(y)
• Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3]
[4, 5, 6]
14/11/2025 DEPARTMENTOFBME 80
Immutable operations
• *
• This operation will replicate a list to the
specified number of times.
x = [1, 2, 3]
print(x * 3)
print(x)
• Output:
• [1, 2, 3, 1, 2, 3, 1, 2, 3]
• [1, 2, 3]
14/11/2025 DEPARTMENTOFBME 81
Immutable operations

• min
• This method returns the smallest element in
a list.
x = [40, 100, 3, 9, 4]
print(min(x))
print(x)
• Output:
3
[40, 100, 3, 9, 4]
14/11/2025 DEPARTMENTOFBME 82
Immutable operations
• max
• Unlike the min method, this returns the
largest item in a list.
x = [40, 100, 3, 9, 4]
print(max(x))
print(x)
• Output:
100
[40, 100, 3, 9, 4]
14/11/2025 DEPARTMENTOFBME 83
Immutable operations
• index
• Returns the position in the list of the specified
element.
x = [10, 30, 20]
print([Link](30))
print(x)
• Output:
1
[10, 30, 20]
14/11/2025 DEPARTMENTOFBME 84
Immutable operations
• count
• Returns the number of times the specified
item occurs in the list.
x = [10, 30, 20, 30, 30]
print([Link](30))
print(x)
• Output:
3
[10, 30, 20, 30, 30]

14/11/2025 DEPARTMENTOFBME 85
Immutable operations
• sum
• This method sums the items of the list, just if they
can be summed. Sum is a widely used method with
numeric type lists.
x = [2.5, 3, 3.5]
print(sum(x))
print(x)
• Output:
9.0
[2.5, 3, 3.5]
14/11/2025 DEPARTMENTOFBME 86
Immutable operations
• in
• Returns only two possible values ​True when the element is in
the list, and False when it is not. This method is widely used
to avoid exceptions in methods such as: index and remove. In
case that the searched element is not found in the list, it will
result in an exception.
x = ['h', 2, 'a', 6, 9]
print('a' in x)
print(x)
• Output:
True
['h', 2, 'a', 6, 9]
14/11/2025 DEPARTMENTOFBME 87
Loop Lists

• Loop Through a List


• You can loop through the list items by using a for
loop:
• Example
• Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)
• Output:
• apple
• banana
• cherry
14/11/2025 DEPARTMENTOFBME 88
Loop Through the Index Numbers
• You can also loop through the list items by referring to their index
number.
• Use the range() and len() functions to create a suitable iteratable.
• Example
• Print all items by referring to their index number:

thislist = ["apple", "banana", "cherry"]


for i in range(len(thislist)):
print(thislist[i])
• Output:
• apple
• banana
• cherry
14/11/2025 DEPARTMENTOFBME 89
Using a While Loop
• You can loop through the list items by using a while loop.

• Use the len() function to determine the length of the list, then start at 0 and loop your
way through the list items by refering to their indexes.

• Remember to increase the index by 1 after each iteration.

• Example
• Print all items, using a while loop to go through all the index numbers
thislist = ["apple", "banana", "cherry"]
i=0
while i < len(thislist):
print(thislist[i])
i=i+1
• Output:
apple
banana
cherry
14/11/2025 DEPARTMENTOFBME 90
LIST OPERATIONS
[Link] of list
[Link] of list

14/11/2025 DEPARTMENTOFBME 91
CONCATENATION
• Concatenation: the '+' operator
concatenate list
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = a+b
• C=[1,2,3,4,5,6]

14/11/2025 DEPARTMENTOFBME 92
REPETITION
• Repetition: the '*' operator repeats a list a
given number of times
• >>> a = [1,2,3]
• >>> b = [4,5,6]
• >>> print (a*2)= [1,2,3,1,2,3]

14/11/2025 DEPARTMENTOFBME 93
List looping: (traversing a list)

• 1. Looping in a list is used to access every


element in list
• 2."for loop" is used to traverse the elements in
list
• eg:
mylist = ["python","problem",100,6.28]
for i in range (len (mylist)):
print (mylist [i])

14/11/2025 DEPARTMENTOFBME 94
[Link] Slices
• A subset of elements of list is called a
slice of list.
• Ex: n = [1,2,3,4,5,6,7,8,9,10]
• print (n[2:5])
• print (n[-5])
• print (n[5: ])
• print (n[ : ])

14/11/2025 DEPARTMENTOFBME 95
[Link] and cloning
•when more than one variables refers to the
same objects or list, then it is called aliasing.
a= [5,10,50,100]
b=a
b[0] = 80
print ("original list", a) = [5,10,50,100]
print ("Aliasing list", b) = [80,5,10,50,100]
•Here both a & b refers to the same list.
Thus, any change made with one object will
affect other, since they are mutable objects.
•In general, it is safer to avoid aliasing when
we are working with mutable objects .
14/11/2025 DEPARTMENTOFBME 96
5. Cloning

•Cloning creates a new list with same


values under another name. Taking any
slice of list create new list.
•Any change made with one object will not
affect others. the easiest way to clone a
new list is to use "slice operators"
a = [5,10,50,100]
b= a[ : ]
b[0] = 80
Print (" original list", a) = [5,10,50,100]
Print (" cloning list", b) = [5,10,50,100]
14/11/2025 DEPARTMENTOFBME 97
List parameter
•List can be passed as arguments to functions the list arguments
are always passed by reference only.
•Hence, if the functions modifies the list the caller also changes.
• Ex:
def head ():
del t[ 0 ]
>>> letters = ['a','b','c']
>>> head (letters)
>>> letters
• ['b','c']
• The parameters 't' and the variable 'letters' or aliases for the
same objects
• An alternative way to write a function that creates and return a
new list
14/11/2025 DEPARTMENTOFBME 98
List parameter

• def tail (t):


• return t [1:]
• >>> letters = ['a','b','c']
• >>> result = tail (letters)
• >>> result ['b','c']
• In above, The function leaves the original
list unmodified and return all element in list
except first element

14/11/2025 DEPARTMENTOFBME 99
• Recall
• List
• List access method-loop, index
• List methods or functions
• Loop list
• List operations-mutable, immutable
• List aliasing, cloning
• List parameter-list passed as a argument
to function-variable length argument, pass
by reference
14/11/2025 DEPARTMENTOFBME 100

You might also like