Python notes 45
Python notes 45
Syllabus
MODULE 1
Introduction to Python - The IDLE Python Development Environment - The Python Standard Library - Literals -
Numeric Literals - String Literals - Control Characters - String Formatting - Implicit and Explicit Line Joining Variables
and Identifiers - Variable Assignment and Keyboard Input- Identifier-Keywords and Other Predefined Identifiers in Python
– Operators - Various Operators - Relational Operators-Membership Operators – Boolean Operators - Expression and
Data Types -Operator Precedence and Boolean Expressions - Operator Associativity - Mixed-Type Expression
MODULE 2
Control Structure -Selection Control- If Statement - Indentation in Python - Multi-Way Selection - Iterative Control -
While Statement - Input Error Checking - Infi nite loops - Definite vs. Indefinite Loops
MODULE 3
List Structures - Common List Operations - List Traversal - Lists (Sequences) in Python- Python List Type -
Tuples- Sequences- Nested Lists Iterating Over Lists (Sequences) in Python - For Loops - The Built-in range Function
- Iterating Over List Elements vs. List Index Values-While Loops and Lists (Sequences) - Dictionaries and sets
MODULE 4
Defining Functions - Calling Value-Returning Functions - Calling Non-Value-Returning Functions - Parameter Passing -
Keyword Arguments in Python Default Arguments in Python - Variable Scope - Recursive functions - Exception Handling
-The Propagation of Raised Exceptions - Catching and Handling Exceptions -Exception Handling and User Input
MODULE 5
String Processing - String Traversal - String-Applicable Sequence Operations -String Methods - Using Text Files -
Opening Text Files - Reading Text Files - Writing Text Files
TEXT BOOK
1, Charles Dierbach, Introduction to Computer Science using Python , Wiley First Edition (2015),ISBN-10:
81265560132015
REFERENCE BOOKS
1, Zed A.Shaw, Learn Python the Hard Way Paperback, Pearson Education, Third Edition edition(2017), ISBN-10:
9332582106
2. Paul Barry, Head First Python, O' Reilly Publishers, First Edition, 2010, ISBN:1449382673.
PYTHON PROGRAMMING
UNIT – I
Python is a dynamic, high level, free open source and interpreted programming language.
It supports object-oriented programming as well as procedural oriented programming.
It was initially designed by Guido van Rossum in 1991 at Centrum Wiskunde & Informatica (CWI) which is
situated in Netherland.
The inspiration for the name came from BBC’s TV Show – ‘Monty Python’s Flying Circus’, as he was a big
fan of the TV show and also he wanted a short, unique and slightly mysterious name for his invention and
hence he named it Python!
It was mainly developed for emphasis on code readability, and its syntax allows programmers to express
concepts in fewer lines of code.
Due to its elegance and simplicity, top technology organizations like Dropbox, Google, Quora, Mozilla, Hewlett-
Packard, Qualcomm, IBM, and Cisco have implemented Python.
Features in Python
There are many features in Python, some of which are discussed below –
1. Simplicity
a. Python is its own kind of simple. All you need to know is how the indentations work and you can code
the most complex of problems in the fewer lines of code.
2. Open Source
a. Python is free for anyone to use. You even have the freedom to modify the code of Python to
better your own needs without facing any repercussions.
3. Portability
a. Code writing can be done once and run across different systems without any changes. This makes it
super helpful when a team works on a project.
4. Embedding Properties
a. Python allows the code of other languages such as C, C++ to be embedded, which makes it much more
powerful and versatile.
5. Interpretation
a. As you know, Python is compiled line-by-line, making debugging easier and memory management much
more efficient
6. Library Support
a. Python supports libraries that you can use and get started off to obtain your solutions much faster
and easier. And the community for these libraries is very active and helpful
7. OOPS
a. Object-Oriented concepts help you replicate real-world scenarios in your code and also
provide security to them so that you can obtain a well-made application
8. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython in python. PyQt5 is
the most popular option for creating graphical apps with Python.
9. Dynamically Typed Language:
Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a
variable is decided at run time not in advance because of this feature we don’t need to specify the type
of variable.
Applications:
Web Development
Game Development
Machine Learning and Artificial Intelligence
Data Science and Data Visualization
Desktop GUI
Web Scraping Applications
Business Applications
Audio and Video Applications
CAD Applications
Embedded Applications
IDLE can be used to execute a single statement just like Python Shell and also to create, modify, and
execute Python scripts.
Python shell window (interactive interpreter) with colorizing of code input, output, and error messages
IDLE provides a fully-featured text editor to create Python script that includes features like syntax
highlighting, autocompletion, and smart indent.
To start an IDLE interactive shell, search for the IDLE icon in the start menu and double click on it.
To execute a Python script, create a new file by selecting File -> New File from the menu.
press F5 to run the script in the editor window. The IDLE shell will show the output.
1. A Python library is a reusable chunk of code that you may want to include in your programs/ projects.
2. These libraries are the collection of modules, classes which can be used easily.
3. A module is a file containing python definition, functions, variables, classes and statements. The extension of
this file is “.py”.
4. The Python Standard Library is a collection of exact syntax, token, and semantics of Python. It comes bundled
with core modle Python distribution. We mentioned this when we began with an introduction.
5. It is written in C, and handles functionality like I/O and other core modules. All this functionality together
makes Python the language it is.
6. More than 200 core modules sit at the heart of the standard library. This library ships with Python.
7. But in addition to this library, you can also access a growing collection of several thousand components from
the Python Package Index (PyPI)
8. “import” command is used to import the library file into our program.
Import math
ii. from <module>import<object> : It imports only the object which belongs to the module.
It will import only pi value from math module but not entire module.
1. Matplotlib: It helps with data analyzing, and is a numerical plotting library. We talked about it in Python for
Data Science.
2. Pandas : It provides fast, expressive, and flexible data structures to easily (and intuitively) work with
structured (tabular, multidimensional, potentially heterogeneous) and time-series data.
3. NumPy : It has advanced math functions and a rudimentary scientific computing package.
4. SQLAlchemy :SQLAlchemy is a library with well-known enterprise-level patterns.It was designed for efficient and
high-performing database-access.
5. BeautifulSoup : It may be a bit slow, BeautifulSoup has an excellent XML- and HTML- parsing library for
beginners.
Advantages–
– Its biggest advantage is that we can import its functionality in any program and use it.
– Re-usability is one of the biggest advantages.
– It helps in logically organization of Python code.
– Programming becomes very easy when we use the collection of same types of codes.
– Categorization : same attributes can be stored in one module.
Tokens:
Tokens are the smallest individual unit of a program. Tokens in the python are as follows
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Delimiters
1. Keywords:
They are the words convey a special meaning to the Python interpreter .
False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',‘except', 'finally', 'for', 'fro
m', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or','pass', 'raise', 'return', 'try', 'while', 'with', 'yield'
2. Identifiers:
Identifiers are generally defined by users. They are used to name a variable, constant, function, class, or array.
x,y,Sum , AVERAGEr,a1,_carname,$radius,name_list
3. Literals:
Literals means the value which is assigned to the variable. The value of a literals fixed can not be changed.
Types of literals:
i. String Literal
ii. Numeric Literal
iii. Boolean Literal
iv. Special Literal
i. String Literal :
There are multiple ways to specify string literal that basically forms various types.
When we intend to use multiple lines for specifying the string, that becomes a multiline string literal. In order to
accomplish this, backslash ‘\’ is used.
Ex : t = "Hi!\
How are you?"
ii. Numeric Literals:
Numeric literals are of multiple types based on the number type and size.
They are immutable and there are three types of numeric literal :
1. Integer
2. Float
3. Complex.
Integer literal:
Both positive and negative numbers including 0. There should not be any fractional part.
Binary literals starts with 0b, Octal literals starts with 0o and Hexadecimal literals starts with 0x.
Examples:
Binary Literals
a = 0b10100
Decimal Literal
b = 50
Octal Literal
c = 0o320
Hexadecimal Literal
d = 0x12b
print(a,b,c,d)
Output :
20 50 208 299
Float literal:
These are real numbers having both integer and fractional parts.
Example: e = 24.8
f = 45.0
z = 7 + 5j
k = 7j
print(z, k)
Output:
(7+5j) 7j
Example:
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7
print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)
Output
a is True
b is False
c: 4
d: 7
v. Special literal:
None literal is used to denote an absence of a value.
Example:
A= None
4. Operators:
Ex : 10 + num
The value 10, and the variable num are operands. the + (plus) sign is an operator.
Unary Operators:
. For eg.
unary +, unary - operator.
Arithmetic operators
Relational or Comparison Operators
Assignment operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators:
Python supports arithmetic operators that are used to perform the four basic arithmetic operations as
well as modular division, floor division and exponentiation
Relational operator compares the values of the operands on its either side and determines the relationship among them.
num2 = 0,
Ex: M=10+5
Logical Operators
There are three logical operators supported by Python. These operators (and, or, not) are to be written in
lower case only.
The logical operator evaluates to either True or False based on the logical operands on either side.
Every value is logically either True or False.
By default, all values are True except None, False 0 (zero)
More Examples:
1. >>> NOT(5>10)
TRUE
2. >>> (10<5) OR (15>20)
FALSE
Identity Operators
Identity operators are used to determine whether the value of a variable is of a certain type or not.
Identity operators can also be used to determine whether two variables are referring to the same object or not.
There are two identity operators
Membership Operators
Membership operators are used to check if a value is a member of the given sequence or not.
Bitwise Operators
<< Zero fill left Shift left by pushing zeros in from the right and let the
shift leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in from the
shift left, and let the rightmost bits fall off
Example for Bitwise Operators:
a=0b0010
b=0b0011
print(a&b)
Print(15>>2) 1111>>2 0111 0011
Output:
2
3
Delimiters:
They the are symbols used to organize program structure and statements..
{ }, [ ], ( ), , , ; , :
EXPRESSION:
An expression is defined as a combination of constants, variables, and operators.
An expression always evaluates to a value.
A value or a standalone variable is also considered as an expression but a standalone operator is not an
expression.
Example :
(i) 100 (iv) 3.0 + 3.14
(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"
Boolean Expression:
A boolean expression is an expression that evaluates to a boolean value. The equality operator, ==, compares two
values and produces a boolean value related to whether the two values are equal to one another.
Example :
x=(5 == 5)
y=(5 == 6)
print(x)
print(y)
Output:
True
False
Precedence of Operators
Evaluation of the expression is based on precedence of operators.
When an expression contains different kindsof operators, precedence determines which operator should be
applied first.
Higher precedence operator is evaluated before the lower precedence operator.
The unary operators need only one operand, and they have a higher precedence than the binary operators.
The minus (-) as well as + (plus) operators can act as both unary and binary operators, but not is a unary
logical operator.
The following table lists precedence of all operators from highest to lowest.
Operators Associativity:
When two operators have the same precedence, associativity helps to determine the order of operations.
Associativity is the order in which an expression is evaluated that has multiple operators of the same
precedence. Almost all the operators have left-to-right associativity.
Comments:
Variables in Python:
Variables are like containers which are used to store the values for some input,intermediate result of
calculations or the final result.
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Variables do not need to be declared with any particular type, and can even change type after they have
been set.
Variable names are case sensitive. For eg. num and NUM are treated as two differentvariable names.
Keywords should not be used as the variable names.
Variable names should be short and meaningful.
All variable names must begin with a letter or an underscore (_).
After the first letter, variable names may contain letters and digits (0 to 9) and anunderscore (_),
no spaces or special characters are allowed.
EXAMPLES
a=17
name='Rachit'
num=10.5
NOTE : Variables do not need to be declared with any particular type and can evenchange type after they have been s
et
EXAMPLE
num=10
num = 'Raman'
Output A Variable
PRINT statement
Syntax:
print(*objects, [sep=’ ‘ or <separator-string> end=’\n’ or <end-string>])
>>>x="welcome"
>>>print (x)
welcome
>>> x="Year"
>>> y="New"
>>> print(y + x)
NewYear
output:
5
7
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format()
method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using
numbers (tuple index).
INPUT A VARIABLE
input statement
To get input from user interactively, you can use built-in function input().
input() returns the value which is usually stored in a variable.
Input function always returns a string value.
Syntax:
Variable name = input(<prompt to be displayed>)
For example:
>>>name = input("What is your name?")
To input numeric data from input() function we can use typecasting, i.e.,changing the datatype using function.
The string data accepted from the user can be converted to appropriate numericdata type using int(), float()
and eval() functions
>>>y=int (input("enter your marks"))
m=y+5
print(m)
enter your marks 92
97
DATA TYPES
Data type states the way the values of that type are stored, the operations that can bedone on that type,
and the range for that type.
Different types of data like character, integer and numbers with decimals etc. can bestored in variables.
Different kinds of data require different amount of memory for storage.
1. Number
Number data type is used to store Numerical Values.
Python supports three different numerical types
1. integer
2. float point numbers
3. complex numbers
In addition, Booleans are a subtype of integers.
1) Integer: Integer are whole numbers without decimal point. They can be positive or negativewith unlimited length.
For example:
>>>a=20
Integers contain Boolean Type which is a unique data type, consisting of two constants,
True & False.
A Boolean True value is Non-Zero, Non-Null and Non-empty.
For example:
>>>entry=true
2)Floating point numbers: Numbers with fractions or decimal point are called floating point numbers.
Forexample:
>>> k=200.789
c) Complex Numbers: A complex number is an ordered pair of two floating-point numbers denoted by a + bi,where a
and b are the real numbers and i is the imaginary unit. For example:
>>>x=10+5i
For accessing different parts of variable a; we will use a.real and a.imag.
>>>print (x.real, x.imag)
10.0 5.0
2. STRINGS
String is an ordered set of characters enclosed in single or double quotation marks.
Strings are immutable.
Each character can be individually accessed using its index.
Valid string indices are 0,1,2,….upto length-1 in forward direction and -1,-2,-3,….-length in backward direction .
For example:
>>>str="I love Python"
Print(str[2])
Print(str[-1])
Output: l
n
3. LISTS
A list is a collection of comma-separated values (items) within square brackets.
Values in the list can be modified, i.e. it is mutable.
The values that make up a list are called its elements.
Elements in a list need not be of the same type.
EXAMPLES
list1=[100, 200, 300, 400, 500]
list2=["Raman", 100, 200, 300, "Ashwin"]
list3=["A", "E", "I", "O", "U"]
4. TUPLE
5. DICTIONARY
Python dictionary is an unordered collection of items where each item is a key: valuepair.
We can also refer to a dictionary as a mapping between a set of keys and a set ofvalues.
Each key is separated from its value by a colon (:),the items are separated by commas andthe entire dictionary
is enclosed in curly braces.
Dictionary is mutable.
We can add new items or change the value of existing items.
EXAMPLES
dict1={'R':'RAINY' , 'S':'SUMMER', 'W':'WINTER' , 'A':'AUTUMN'}
dict2={1: 'robotics', 2:'AR' , 3:'AI' , 4:'VR'}
dict3={'num':10, 1:20}
. We can use the type() function to know the data type of a variable. For example:
>>>num=10
>>> type(num)
<class 'int'>
>>> name='Kapil'
>>> type(name)
<class 'str'>
Mutable and Immutable types:
Mutable:
The Mutability means that in the same memory address, new value can be stored as and when required.
Mutable types are those whose values can be changed to place.
Mutable types in Python are
Lists, dictionaries and sets.
Ex:
A=[1,2,3]
A[1]=20
It will change the A as [1,20,3]
Immutable :
The immutable types arethose that can never change their value in place. In Python the following are immutable
types
Integers, floating point numbers, Booleans, strings, tuples.
EXAMPLE
>>> x= 158.19
>>> y= int(x)
>>> print (y)
158
EXAMPLE
>
>>>y=float(x)
>>>print y
165.0
iii)A backslash can continue only string literals. It cannot continue any other literals type.
Trying to continue the integer literals using ‘\’ render an error message.
Example:
>>> x> 80andx< 100| \
y<101andx < y
True
>>> a<100andb>20| \
a>100andc>100| \
b<50| c>=100
False
In Python implicit line joining we uses parentheses, square brackets or curly braces to split the expression in multiple
lines. For instance consider the code below.
'Nov' , 'Dec' )
'Saturday' , 'Sunday' }
'new',
'old'}
iii)Triple-quoted strings are also allowed to have continued lines but here there cannot be comment in each line.
>>> tri_str
Assignment :
A program’s control flow is the order in which the program’s code executes.
The control flow of a Python program is regulated by conditional statements, loops, and function calls.
Sequential statements are a set of statements whose execution process happens in a sequence.
Example:
a=20
b=10
c=a-b
print("Subtraction is : ",c)
In Python, the selection statements are also known as Decision control statements or branching statements.
The selection statement allows a program to test several conditions and execute instructions based on which
condition is true.
1. Simple if
2. if-else
3. nested if
4. if-elif-else
1. Simple if: If statements are control flow statements that help us to run a particular code, but only when a
certain condition is met or satisfied. A simple if only has one condition to check.
Syntax:
If <conditional expression>:
Statement
[statements]
Flow Control:
Example:
n = 10
if n % 2 == 0:
2. if-else: The if-else statement evaluates the condition and if the condition evaluates to True, it carries out
statements indented below if statement, but if the condition is False, then the body of else is executed.
Syntax:
If <conditional expression>:
Statement(s)
else:
statement(s)
Flow Control:
Example:
Check whether the given no is positive or negative.
n = int(input(“Enter a number : ”)
if n % 2 == 0:
print("n is even")
else:
print("n is odd")
If condition:
If condition:
statement(s)
else:
statement(s)
else:
statement(s)
Flow Control:
Example: Write a program in python to find the biggest of three numbers
if a > b:
if a > c:
else:
elif b > c:
else:
print("c is big")
4. if-elif-else: Python evaluates each expression one by one and if a true condition is found the statement(s)
block under that expression will be executed. If no true condition is found the statement(s) block under else
will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
..
else:
statement
Flow Control:
Example: Program to check whether the given number is positive, negative or zero.
if a<0:
elif a==0:
else:
Whenever there is only a single statement to be executed inside the if block then shorthand if can be used.
The statement can be put on the same line as the if statement.
Syntax:
if condition: statements
Example:
# Python program to illustrate short hand if
i = 10
if i< 15: print("i is less than 15")
Output:
i is less than 15
This can be used to write the if-else statements in a single line where there is only one
statement to be executed in both if and else block.
Syntax:
statement_when_True if condition else statement_when_False
Example:
Output:
True
Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python,
however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented line.
The amount of indentation is up to you, but it must be consistent throughout that block.
Generally, four whitespaces are used for indentation and are preferred over tabs. Here is an example.
if i == 5:
break
In Python, the iterative statements are also known as looping statements or repetitive statements. The
iterative statements are used to execute a part of the program repeatedly as long as a given condition is
True.
1. while statement
2. for statement
3.
The while statement is also known as entry control loop statement because in the case of the while statement,
first, the given condition is verified then the execution of statements is determined based on the condition
result.
Python while loop is used to repeat a block of code until the specified condition is False.
The while loop is used when we don’t know the number of times the code block has to execute
Syntax:
while condition:
Statements
Flow Control :
Example:
i=1
sum=0
while i<= n:
sum=sum+i
i += 1
print(“Sum = “,sum)
In Python, the else clause can be used with a while statement. The else block is gets executed whenever the
condition of the while statement is evaluated to false. But, if the while loop is terminated with break
statement then else doesn't execute.
Example:
In Python, the for statement is used to iterate through a sequence like a list, a tuple, a set, a dictionary, or
a string. The for statement is used to repeat the execution of a set of statements for every element of a
sequence.
Syntax
for <variable> in <sequence>:
Statements
In the above syntax,the variable is stored with each element from the sequence for every iteration.
Flow control
my_list = [1, 2, 3, 4, 5]
print(value)
Output:
s=input(“Enter a string : “)
for i in s:
print(i)
Output:
h
e
l
l
o
# Python code to illustrate for statement with Tuple
my_tuple = (1, 2, 3, 4, 5)
print(value)
In Python, the else clause can be used with a for a statement. The else block is gets executed whenever the
for statement is does not terminated with a break statement. But, if the for loop is terminated with break
statement, then else block doesn't execute.
# Here, else block is gets executed because break statement does not execute.
for i in range(1,n):
if i>10:
print(“hello”)
else:
break
continue
Pass
Break Statement
The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.
Syntax:
break
Flow Control:
The working of break statement in for loop and while loop is shown below.
if val == "i":
break
print(val)
Output:
Output:
12
16
Continue Statement:
The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
Loop does not terminate but continues on with the next iteration.
Syntax:
continue
Flow Control
Example: print the contents of a string except ‘i’
if val == "i":
continue
print(val)
Output:
pass Statement:
Syntax:
Pass
Example:
pass
2.3.4 : RANGE() FUNCTION:
Syntax:
range (stop)
Stop:
To generate the numbers in sequence up to “stop-1” numbers. It will start from zero.
Ex:
range(5)=[0,1,2,3,4]
Syntax :
Start:
Stop:
Syntax:
Start:
Generating the numbers starting from “start”
Stop:
To generate a number in sequence up to “stop-1” numbers.
Step:
difference between each number in the sequence
for i in range(15):
print(i+1)
sum=0
for i in range(1,11):
sum=sum+i
print("Sum = ",sum)
for i in range(1,100,2):
print(i)
Output:
enter the number5
5X1=5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
(OR)
while expression:
while expression:
statement(s)
statement(s)
Example:
-------------------------------------------------------------------------------------
Write a program to print the following pattern:
12345
1234
123
12
1
n=5
s=0
for i in range(n,0,-1):
for j in range(1, i+1):
print(j, end= ' ')
print()
--------------------------------------------------------------------------
Output:
enter no.of elements : 5
enter a number : 45
enter a number : 3
enter a number : 78
enter a number : 30
enter a number : 12
Maximum number is : 78
Minimum number is : 3
2.4: Input Error Checking
This occurs when we have asked the user for input but have not provided any input in the input box. We
can overcome this issue by using try and except keywords in Python.
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because
of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a
loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run continuously so that client
programs can communicate with it as and when required.
Example:
i=1
while True:
if i==4:
break;
print(i)
i=i+2
In definite loops, the number of iterations is known before we start the execution of the body of the loop.
for I in range(1,11):
print(‘*’)
In indefinite loops, the number of iterations is not known before we start to execute the ody of the loop, but
depends on when a certain condition becomes true (and this depends on what happens in the body of the loop)
Example: while the user does not decide it is time to stop, print out a * and ask the user whether he wants
to stop.
2 Marks
1. Define if statement.
a,b,c=2,3,4
a,b,c=a*a,a*b,a*c
print(a,b,c)
6. Write a program to print the area of circle when radius of the circle is given by user.
8. What are loops in Python? How many types of loop are there in Python?
5 Marks
10 Marks
List is a standard data type of Python that can store a sequence of values belonging to any type.
Lists are mutable (modifiable), that means we can change the elements of a list in place.
The index value starts from 0 and goes on until the last element called the positive index.
There is also negative indexing which starts from -1 enabling you to access elements from the last to first.
Ex: a=[1,2,3,4]
Names=[“ram”,”Sam”,”Anil”]
L=[value1,value2,……..]
Examples:
>>> l1=list(‘hello’) # creating list from string
>>>print(l1)
[‘h’,’e’,’l’,’l’,’o’]
>>> t=(‘w’,’e’,’l’,’c’,’o’,’m’,’e’)
Adding elements
Deleting elements
Joining Lists
Replicating List
Traversing a List
Adding Elements
Adding the elements in the list can be achieved using the append(), extend() and insert()
functions.
The append() method adds a single item to the end of the list.
L.append(item)
>>>L1.append(20)
>>>L1
[1, 2, 3, 4, 20]
Syntax:
List. insert(<pos>,<item>)
Ex:
>>>vowels=[‘a’, ’e’,’o’,’u’]
>>>vowels. Insert(2,’i’)
>>>vowels
[‘a’,’e’,’i’,’o’,’u’]
The extends() method is also used for adding multiple elements to a list.
Syntax:
List.extend(<list>)
Ex:
>>>L1=[1,2,3]
>>>L2=[4,5,6]
>>>L1.extend(L2)
>>>L1
[1,2,3,4,5,6]
To update or change an element of the list in place, you just have to assign new value to the element’s index in list
.
Syntax:
Example:
>>>list1=[10,20,30,40]
>>>list1[2]=25
>>>list1
[10,20,25,40]
del statement
We can delete elements from list using del statement. del statement can remove an individual item or all items
identified by a slice or entire list.
Syntax:
>>>L=[1,2,3,4,5,6,7,8]
>>> L [1, 2, 4, 5, 6, 7, 8]
>>>del L
pop() method
The pop() removes an element from the given position in the list, and return it. If no index specified, pop()
removes and return the last item in the list.
Example:
>>> a=[‘a’,’b’,’c’,’d’,’e’]
>>> x
‘a’
>>>y=a.pop()
>>>y
‘e’
>>> a
[‘b’,’c’,’d’]
remove() method
The remove() method removes the first occurrence of the given value in the list.
Syntax:
List.remove(<value>)
Example:
>>> a=[1,2,3,4,5,6,7,8]
>>>a.remove(2)
>>>a
[1,3,4,5,6,7,8]
Slicing the list
Syntax:
Seq = list[start:stop:[step]]
Example:
Joining a Lists
To join Lists,+ operator , is used which joins a list at the end of other list.
With + operator, both the operands should be of list type otherwise error will be generated.
Example:
>>>l1=[1,2,3,4]
>>>l2=[5,6,7]
>>>l3=l1+l2
>>>l3
[1, 2, 3, 4, 5, 6, 7]
Replicating List
To replicate a list, * operator , is used. It repeats the elements of the list n number of times.
Traversing a List
Traversal of a list means to access and process each and every element of that list.
Syntax:
Example:
Output:
‘P’
‘Y’
‘T’
‘H’
‘O’
‘N’
3.1.3..List functions:
Example:
Example:
Example:
Example:
5. pop(): Delete and return the element of passed index. If the index is not passed
element from last will be deleted.
Syntax:
List.pop( [<index>] )
Example:
6. remove() : It will delete the first occurrence of passed value but does not return
the deleted value.
7. clear() : It will delete all values of the list and gives an empty list.
Syntax:
List.clear()
Example:
>>>lst = [13,18,11,16,18,14]
>>>lst.clear()
>>>lst
[]
8.sort() : It will sort the elements in ascending order. To sort the list indescending order we need to write
list.sort(reverse=True).
Syntax:
List.sort()
Example:
9. count() : It will count and return the number of occurrences of the given item.
Syntax:
List.count(<item>)
Example:
>>>lst = [13,18,11,16,18,14]
>>>lst.count(18)
2
10. reverse(): It will reverse the list but it does not create a new list.
Syntax:
List.reverse()
Example:
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:
>>>x
['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
>>> x [1][1]
['ccc', 'ddd']
>>> x [1][2]
'ee'
print(x[3][0],x[3][1])
hh ii
>>> x[1][1]
['ccc', 'ddd']
ccc ddd
In Python, tuple is also a kind of container which can store list of any kind of values.
Tuple is an immutable data type which means we cannot change any value of tuple.
Tuple is a sequence like string and list but the difference is that list is mutable whereas string and tuple are
immutable.
In Python, “()” parenthesis are used for tuple creation.
T= ()
T=tuple ()
T=(value,)
T=(value1,value2,value3…….)
tuple() function is used to create a tuple from other sequences. See examples-
1) From STRING
2) From LIST
3) By input
>>>t2
Traversing
Joining
Deleting tuple
Replicating
Slicing
Unpacking tuple
Traversing a Tuple:
Traversing means accessing each element of a tuple. The for loop makes it easy to traverse a tuple.
Syntax:
Example:
T = (1, 2, 3, 4, 5)
for a in T:
print (a)
Joining Tuples
The ‘+’ operator is used to join two tuples. It concatenates two tuples.
Example:
>>> T2 = (‘a’,’b’,’c’,’d’)
>>> T3=T1+T2
>>> T3
Deleting a Tuple:
Deleting individual elements is not possible in tuple, because it is an immutable. But we can delete the entire tuple using
del statement.
Example:
>>> del T
>>> T
Replicating Tuples:
Like list and strings ‘*’operator is used to replicate(repeat) a tuple specified number of times.
>>> t = ( 1,2,3)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
Example:
>>> t = (10,20,30,40,50,60,70)
>>>x = t [2:5]
>>>x
(30,40,50)
>>> y
Unpacking Tuples:
Creating a tuple from a set of values is called packing and its revers, i.e., creating individual values from a tuple’s
elements is called unpacking.
Syntax:
<variable1>,<variable2>,<variable3>,…. = t # t is tuple
Example:
t=(1,2,’hello’,’hai’)
a,b,c,d=t
print(a,b,c,d)
1 2 ‘hello’ ‘hai’
1. len(): This method returns length of the tuple, i.e., the count of elements in the tuple.
Syntax:len(<tuple>)
Example:
>>len(employee)
2. max(): This method return the maximum value from the elements of the tuple.
Syntax: max(<tuple>)
Example:
>>>tp = (23,10,5,78,123,34)
>>>max(tp)
123
3. min(): This method returns the minimum value from the elements of the tuple.
Syntax: min(<tuple>)
Example:
>>>tp = (23,10,5,78,123,34)
>>>min(tp)
Example:
>>> t = (1,2,3,4,5)
>>>t.index(3)
Syntax:<tuple>.count(<value>)
Example:
>>> t = (1,2,3,3,6,7,2,8,2,0)
>>>t.count(2)
Syntax: tuple(<sequence>)
Example:
>>> t= (“hello”)
>>> t
(‘h’,’e’,’l’,’l’,’o’)
To create a dictionary you need to include the key:value pairs in curly braces.
Example:
The elements of the dictionary are accessed through the keys defined in the key:value pair.
<dictionary-name>[“key”]
Ex:
>>> emp[“age”]
24
>>>emp.keys()
>>>emp.values()
[10000,24,’john’]
Traversal of a collection means accessing and processing each element of it. The for loop makes it easy to traverse.
Example:
D1={5: “number”,”a”:”string”,1.2:”float”}
for k in D1:
print(key,”:”,D1[key])
Output:
5 : number
a : string
1.2 : float
Adding Elements:
New element (key:value) can be add to a dictionary by using assignment operator. But the key being added must not
exist in dictionary and must be unique. If the key already exists, then this statement will change the value of existing
key and no new entry will be added to dictionary.
Syntax:
<dictionary>[key]=<value>
Example:
A[4] = "Four"
print(A)
OUTPUT
Updating elements:
<dictionary>[key]=<value>
B[2] = 'Ram'
print(B)
OUTPUT:
Deleting elements:
1. By using del statement : To delete an element (key:value) from dictionary use del statement.
Syntax
del <dictionary-name>[key]
print(B)
OUTPUT:
2. By Using pop() function : This function not only delete the element of required key but also return the deleted
value.
Example:
print(a)
print(B)
OUTPUT
Sunil
To check the existence of a key use member ship operators in and not in operators with dictionaries.
<key> in <dictionary>
Examples:
>>> 1 in B
True
>>> 4 not in B
True
.Ex:
>>>len(emp)
2. clear() – This method removes all items from the dictionary and the dictionary becomes empty.
>>> emp = {‘salary’ : 10000 , ‘age’ :24 , ‘name’ : ‘john’ }
>>>emp.clear()
{}
3. get() – With this method we can get the item with the given key.
>>>emp.get(‘age’)
24
4. items() – This method returns all of the items in the dictionary as a sequence of(key,value) tuples .
emp = {‘salary’ : 10000 , ‘age’ :24 , ‘name’ : ‘john’ }
mylist=emp.items()
for x in mylist :
print(x)
output:
(‘salary’ ,10000)
(‘age’ ,24)
(‘name’, ‘john’)
5. keys() – This method returns all of the keys in the dictionary as a sequence of keys.
>>>emp.keys()
6. values() - This method returns all of the values in the dictionary as a sequence (a list).
>>>emp.values()
[10000, 24, ‘john’]
7. update() – This method merges key:value pairs from the new dictionary into the original dictionary, adding or
replacing as needed . The items in the new dictionary are added to the old one and override any items
already there with the same keys. This method returns all of the keys in the dictionary as a sequence of keys.
>>>emp1.update(emp2)
>>>emp1
Sets can be created by using the built-in set () function with a sequence by placing the sequence inside curly
braces, separated by ‘comma’.
S= set() # creating a blank set
S1= set(“hello”)
>>> b={1,2,3,4,1,4}
>>> b
{1, 2, 3, 4}
Adding an element:
We can add single element by using add() method. To add multiple elements use update() method.
Example:
>>>my_set = {1, 3}
>>>print(my_set)
{1,3}
>>>my_set.add(2)
print(my_set)
{1, 2, 3}
{1, 2, 3, 4, 5, 6, 8}
Removing an element:
A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if the element is not
present in the set. On the other hand, the remove() function will raise an error in such a condition (if element is not
present in the set).
>>>my_set = {1, 3, 4, 5, 6}
>>>print(my_set)
{1,3,4,5,6}
# discard an element
>>>my_set.discard(4)
>>>print(my_set)
{1, 3, 5, 6}
# remove an element
>>>my_set.remove(6)
>>>print(my_set)
{1, 3, 5}
i.Union Operation:
Set union can be performed with the | operator or union method. It eliminate duplicate values and return the
remaining values from the two sets.
Example:
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1 | x2
{'baz', 'quux', 'qux', 'bar', 'foo'}
>>> x1.union(x2)
{'baz', 'quux', 'qux', 'bar', 'foo'}
>>> a | b | c | d
{1, 2, 3, 4, 5, 6, 7}
Example:
>>> x1.intersection(x2)
{'baz'}
>>> x1 & x2
{'baz'}
iii.Difference operation :
Difference is performed using - operator. Same can be accomplished using the difference() method.
>>>A = {1, 2, 3, 4, 5}
>>>B = {4, 5, 6, 7, 8}
>>>print(A - B)
Output:
{1, 2, 3}
>>>A.difference(B)
{1, 2, 3}
iv. Symmetric Difference
Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
print(A^B)
Output:
{1, 2, 3, 6,7,8}
2Marks
5Marks
10Marks
i. Create a dictionary
ii. Traversing