Chapter 3
Getting Started with Python
Introduction- Python programming language was developed by Guido Van Rossum in February 1991.
Python is based on or influenced with two programming languages-
ß ABC language, a teaching language created as a replacement of BASIC.
ß Modula-3
Python is an easy to learn yet powerful object oriented programming language. It is a very high level
programming language yet as powerful as many other middle-level not so high level languages like
C,C++,Java etc.
Plus Point of Python language-
1. Easy to use- Python is compact and very easy to use Object Oriented Language with simple
syntax rules.
2. Expressive language- It is more capable to expressing the code’s purpose than many other
languages.
3. Interpreted language- Python is an interpreted language, not a compiled language.
4. Its Completeness- it has all the required functions through various modules of Python
standard library.
5. Cross-platform Language—Python can run equally well on variety of platforms.
6. Free and Open Source-
7. Python language is freely available.
8. Variety of Usage/Application- this is powerful, complete and useful language over these
years.
Minus Point of Python language-Although python is very powerful language yet simple but it is not
perfect programming language
1. Not the fasted language-Python is an interpreted language not a fully compiled one.
2. Lesser Libraries than C,Java
3. Not Strong on type binding
4. Not easily convertible
Sample python expression
>>> 2+5
7
Interpreter: This language processor convert a HLL (High Level Language) program into machine
language by converting and executing it line by line.
Compiler- It also converts the HLL program into machine language but the conversion manner is
different. It compiles all statements at once.
Print statement- To print the messages or variable’s value on the screen.
Ex-
Print(“Hello how are you?”)
This PDF is created at https://www.pdfonline.com/convert-pdf/
Output – Hello how are you?
Ex-
a=5
b=10
c=a+b
print(“sum=”,c)
output-
sum=15
Chapter 4
Python Fundamentals
Key points– IPO-Input, Process and Output
Tokens- It is the smallest unit in the program is known as token or lexical unit.
Python has following type of tokens-
(A) Keywords- These are the words that convey a special meaning to the language
compiler/interpreter.
ex- false,del ,for, while,if,elif etc.
(B) Identifiers- These are fundamental building blocks of a program and are used as the
general terminology for the names given to different parts of the program.
Like variables name,class name ,list name, dictionaries names etc.
There are some to make the identifiers-
(i) An identifier is a user defined name.
(ii) The first character must be a letter,the underscore(_).
(iii) Upper case or lower case are different types of variables.
(iv) It should not be a keywords.
(v) It can not contain any other symbols or spaces.
(C) Literals/values- These are data items that have a fixed value.
Python has following types of literals
(i) String literals –“ABC”,”Sunil” etc.
(ii) Numeric literals- 10,20 12.6 etc.
(iii) Boolean literals- true or false
(D) Operators- These are the tokens that trigger some computation when applied to variable
and other objects in an expression.
Ex- c=a+b
Here a and b are the operand and + is operator.
(i) Unary Operator- These are those operators that require one operand to operate
the equation
Ex-
+ unary Plus
_ unary minus
(ii ) Binary Operators- Binary operators are those operators that require two operands to
operate the equations
Like-
This PDF is created at https://www.pdfonline.com/convert-pdf/
+ Addition Ex- 2+5=7
- Subtraction Ex- 5-3=2
* multiply Ex- 4*3=12
/ Division Ex- 4/2=2
% Remainder Ex- 5%2=1
** Exponent(power) Ex- 2**3=8
//Floor Division. Ex- 5//2=2 (Lowest,nearest integer)
(iii) Identity Operator-
(a) Is – is the identity same.
(b) Is not – is the identity not same.
(iv) Relational Operators- To compare the values
(a) < Less than
(b) > Greater than
(c) <= Less than or equal to
(d) >= Greater than or equal to
(e) == Equal to
(f) != Not equal to
(v) Logical Operator- to join the conditions.
(a) And Logical AND- To join two or more conditions but all the condition must be true.
(b) Logical OR- To join the tow or more condition and at least one condition should be
true.
(vi) Assignment operators- to assign value or expression into the variable.
It uses equal sign to assign the value into the variables-
Ex- a=10; Here we are assigning the value 10 into the variable a.
It supports all the arithmetic operators in the form of short hand operators.
Ex- a=a+1
Short hand form- a+=1 but it requires two conditions one is both sides variable
must be same and arithmetic operator should be there.
Syntax- variable operator= value
(vii) Membership operator- To check the members are there or not in the list.
(a) In operator- to check weather member is there or not.
(b) Not in – if gives true if the member is not there.
Punctuators- These are symbols that are used in programming language to organize sentence
structure. Like ‘ “ # \ () {} @,”/=
Any Python program can have the following elements-
(a) Expressions- It is simple arithmetic expressions which is legal form of variables or
operators. Ex- c=a+b
(b) Statement- A statement is a programming instruction that does something.
ex- Print(“Hello”)
(c) Comment- These are the additional readable informations.
ex- # this is the program for addition
‘’’ This is the sample of comment in multilines
‘’’
This PDF is created at https://www.pdfonline.com/convert-pdf/
(d) Blocks and Indentation- A group of statements is part of another statement or function.
Ex- if b>5:
Print(“ value b is less than 5”)
Here the print statement is connected to if condition therefore print is written with
indent. If we are not shifting print then it is considered as other statement than it will
execute in both the condition weather it is true or false.
Variables and Assignments-
A variable in python represents named location that refers to a value and whose values
can be used and proceed during program run.
Ex- Marks=70
Name=”raj”
Multiple Assignments-
a=b=c=10
x,y,z=10,20,30
Type function-It gives data type of value
Ex->>>a=10
>>>type(a)
Output : int
Simple input and output-
Input statement -Python provides input statement to ask the value for variable at run time
of the program.
A=input(“enter your name”)
When we will this statement then computer will ask name and whatever users will the name
it will store into the variable A. It asks always string value if we want to do calculation then
forcely we have to convert in integer.
In some Python It uses –raw_input()
Print statement- To print the message or value on the screen.
Print(“hello”)
A=10+20
Print(A)
Or print (“sum=”,A)
Example:
a=int(input("enter no"))
b=int(input("enter no"))
c=a+b
print(c)
This PDF is created at https://www.pdfonline.com/convert-pdf/
Chapter 5
Data Handling
In this chapter we will learn about data types, variables, operators and expressions in
python.
Python provides a predefined set of data types for handling the data it uses. Data can be
stored in any of these data types.
Data Types:
Data can be of many types e.g. character,integer, real, string etc. Anything enclosed in
quotes represents string data in Python. Numbers without fractions represent integer data.
Numbers with fractions represent real data and True and False represent Boolean data.
1. Number data type- Python has following types of data:
(i) Integers:Signed Integer and Boolean(True=1 and False=0)
(ii) Floating point Numbers:Fractional Form and Exponent Notation i.e.3.50003E05
(iii) Complex Numbers-A complex number is made up of both real and imaginary
components like A+Bi
Ex->>>c=0+4.5j
>>>c
4.5j
Note- Python has no character datatype.
2. String data type- A Python string is a sequence of characters and each character can be
individually accessed using its index.
Ex->>>name=’hello’
>>>name[0]
H
Its index no starts from 0 to last character-1.
3. List and Tuples- The list and tuples are Python’s compound data types.
(a) List- A list in python represents a list of comma-separated values of any data types
between square brackets e.g. following are some lists-
Ex- [1,2,3,4,5]
[“raj”,12,”sunil”]
>>>a=[1,2,5,8]
>>>a[0]
1
>>>print(a)
[1,2,5,,8]
(b) Tuples-Ex- >>>p=(1,2,3,4,5)
>>>p
(1,2,3,4)
Note- Values of type list are mutable i.e. changeable- one can
change/add/modify/delete a list elements but values of tuple are immutable(non
changeable).
This PDF is created at https://www.pdfonline.com/convert-pdf/
(c) Dictionary- Dictionary data type is another feature in Python language.The
dictionary is an unordered set of comma-separated key:value pairs, within {}, with
the requirement that within a dictionary, no two keys can be the same .
Ex->>>v={‘a’:1,’e’:2,’I’:3,’o’:4,;u’:5}
>>> v[‘a’]
1
Mutable and immutable data types- The Python data objects are those that can never
change their value in place. Some of the immutable data types are:integer,floating
point numbers,Boolean, strings, tuples.
Some immutable data types are: list,dictionary,set etc.
Variable internals: >>>a=4
>>>type(4)
Int
>>>id(4)
30899132
>>>id(1)
30899132
Operators: The operations being carried out on data, are represented by operators. The
symbols that trigger the operation/action on data, are called operators.
(a) Arithmetic operators- +,-,*,/,%,//,**
This PDF is created at https://www.pdfonline.com/convert-pdf/
(b) Relational Operators: It is used to compare values and give logical true or false result
This PDF is created at https://www.pdfonline.com/convert-pdf/
(c) Assignment operators: It uses equal sign “=” to assign or store values to variables.
This PDF is created at https://www.pdfonline.com/convert-pdf/
Expressions: An expression in Python is any valid combination of operators,literals and
variables. An expression is composed of one or more operators, with operands,
literals and variables as the constituents of expressions.
Ex- String Expressions: “abc”+”xyz”
Output:abcxyz
“abc”*2
Output:”abcabc”
Type casting:Python internally changes the data type of some operands so that all
operands have same data type. This type of conversion is automatic i.e. Implicit and
hence known as implicit type conversion.
Explicit Type Conversion:
An explicit type conversion is user-defined conversion that forces an expression to be
of specific type. The explicit conversion is also known as Type Casting.
<data type>(expression)
Ex- a=3
This PDF is created at https://www.pdfonline.com/convert-pdf/
b=5.0
int(b)- It will be 5 as integer.
float(a)- It will be 3.0 as float.
Some conversion functions are as follows-
Int()- To convert in integer data type.
Float()- To convert in float data type
Str()- To convert in string data type.
Bool()- To convert in Boolean Data type.
Working with math Module of Python-
Python’s standard library provides a module namely math for math related
functions that work with all number types except for complex numbers.
We need to first import math module in our current program using by following
statement-
import math
Then we can use math library’s functions as math.<function name>.
This PDF is created at https://www.pdfonline.com/convert-pdf/
Using random Module-
Python has a module namely random that provides random number
generators.
>>> import random
>>> print(random.random())
0.022353193431
>>> print(random.randint(15,35))
16
>>> random.randrange(11,45)
25
Using the statistics Module-
The statistic module of the python standard Library provides many
statistics functions such as mean(),median(),mode().
>>> import statistics
>>> seq=[5,6,7,5,6,5,5,9,11,12,23,5]
>>> statistics.mode(seq) output:5
>>> statistics.mean(seq) output: 8.25
>>> statistics.median(seq) output: 6.0
Chapter 6
Conditional and iterative statements
Types of statement in Python
Statement are the instructions given to the computer to perform any kind of
action. Python statements can belong to one of the following three types:
1. Empty statement
2. Simple Statement
3. Compound statement
1. Empty statement- The simplest statement is the empty statement. i.e. a
statement which does nothing.
Ex. Pass
This PDF is created at https://www.pdfonline.com/convert-pdf/
2. Simple statement-Any single executable statement is a simple
statement in python.
Ex- name= input(“your name”)
Print (name)
3. Compound Statement- A compound statement represents a group of
statements executed as a unit.
Ex-
If condition:
Statement
Statement Flow Control-
Python is having three type of flow control statements-
1. Sequence- it means the statements are being executed sequentially.
This represents the default flow of statement.
2. Selection- The selection construct means the execution of statement
depending upon a condition test. If a condition evaluates to true, a
course of action is followed otherwise another course of action is
followed.
3. Iteration statement- It means repetition of a set of statement
depending upon a condition test.
Program Logic Development Tools:
An algorithm is a step by step procedure to solve a given problem.
A flowchart is a graphical representation of steps an algorithm to
solve a given problem.
Selection statement –
If statement:
The if statements are the conditional statements in python and these
implement selection constructs (decision constructs).
Ex- if condition:
Statement
Statement
If ..else statement:
This form of if statement tests a condition and if the condition
evaluates to true, it carries out statements indented below if and in
This PDF is created at https://www.pdfonline.com/convert-pdf/
case condition evaluates to false, it carries out statements indented
below else.
Syntax:
If condition:
Statement
Else:
Statement
Ex-
If sales>=1000:
Discount=sales*0.10
Else:
Discount= sales*0.05
If..elif statement: This form of if statement tests a condition and if the
condition evaluates to true, it carries out statements indented below
otherwise else part will be executed but else is also having another
conditions then if the else condition is false then else part will be
executed.
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Other example-
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
One line statement also can be used-
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And Logical Operator-To join two or more conditions.
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
This PDF is created at https://www.pdfonline.com/convert-pdf/
Or Logical Operator-To join two or more conditions but at least one
condition should be satisfied.
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
The pass Statement-
if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to avoid
getting an error.
a = 33
b = 200
if b > a:
pass
short hand if operator
print('kid' if age < 18 else 'adult’)
output :kid
Another Example
>>> age=20
>>> print('kid' if age < 13 else 'teenager' if age < 18 else 'adult')
adult
Python While Loops-
The while Loop
With the while loop we can execute a set of statements as long as
a condition is true.
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
example: to print the table of given no.
i = 1
This PDF is created at https://www.pdfonline.com/convert-pdf/
j=int(input("Enter any no"))
while i <= 10:
c=i*j
print(c)
i += 1 #i=i+1
# program to calculate the sum of all even no and odd no from 1 to 10.
i = 0
s=0
od=0
while i <= 10:
if i%2==0:
s=s+i
else:
od=od+i
i += 1 #i=i+1
print("sum of all even no from 1 to 10:"+str(s))
print("sum of all odd no from 1 to 10:"+str(od))
The break Statement
With the break statement we can stop the loop even if the while condition
is true:
i=1;
while i<=10:
print(i)
if i==5:
break
i+=1
This PDF is created at https://www.pdfonline.com/convert-pdf/
print(“End of program”)
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and
continue with the next:
Example:
i=1
while i<=100:
i+=10 #i=i+10
if i==21:
continue
print(i)
print("end of the program")
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The For Loop-
The for loop of Python is deigned to process the items of any sequence, such as a list or a string, one
by one. The general form of for loop is an follows:
Syntax-
for <variable name> in <sequence>:
This PDF is created at https://www.pdfonline.com/convert-pdf/
Statement1
Statement2
Example-
For a in [1,4,7]: # here [1,4,7] is a value set
Print(a)
Output
1
4
7
Example –
For a in range(1,5):
Print(a)
Output
1,2,3,4
Example
a=int(input("Enter any no for table"))
for b in range(1,11):
c=a*b
print(a,"X",b,"= ",c)
Output-
Enter any no for table17
17 X 1 = 17
17 X 2 = 34
17 X 3 = 51
17 X 4 = 68
17 X 5 = 85
17 X 6 = 102
17 X 7 = 119
17 X 8 = 136
17 X 9 = 153
17 X 10 = 170
>>>
=== RESTART: C:/Users/dev/AppData/Local/Programs/Python/Python37-32/ab.py ===
a=int(input("Enter any no for table"))
for b in range(1,11):
c=a*b
print(a,"is multiplying with ",b,"and product is ",c)
Enter any no for table6
6 is multiplying with 1 and product is 6
6 is multiplying with 2 and product is 12
6 is multiplying with 3 and product is 18
6 is multiplying with 4 and product is 24
6 is multiplying with 5 and product is 30
6 is multiplying with 6 and product is 36
6 is multiplying with 7 and product is 42
6 is multiplying with 8 and product is 48
6 is multiplying with 9 and product is 54
6 is multiplying with 10 and product is 60
This PDF is created at https://www.pdfonline.com/convert-pdf/
For a in range(5,1,-1):
Print(a)
Output
5,4,3,2
Example
for b in "hello brother":
print(b)
Output:
h
e
l
l
o
b
r
o
t
h
e
r
example-
a=input("enter your name:")
for b in a:
print(b)
example-
for a in "india":
print(a)
output
i
n
d
i
a
The else Statement
With the else statement we can run a block of code once when the condition
no longer is true:
Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
This PDF is created at https://www.pdfonline.com/convert-pdf/
Python For Loops-
A for loop is used for iterating over a sequence (that is either a list, a tuple,
a dictionary, a set, or a string).
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
print letter of the word
for x in "banana":
print(x)
for statement with break statement-
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
The range() Function
To loop through a set of code a specified number of times, we can
use the range() function,
for x in range(6):
print(x)
The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and ends at a specified number.
for x in range(2, 6):
print(x)
it will be the no. from 2 to 5.
for x in range(2, 30, 3):
print(x)
it will give the no. from 2 to 29 with increment of 3
else with for statement-
for x in range(6):
print(x)
else:
print("Finally finished!")
This PDF is created at https://www.pdfonline.com/convert-pdf/
Nested Loop:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Chapter 7
Text Handling
Introduction:
Python strings are character enclosed in quotes of any type – single quotation
marks,double quotation marks and triple quotation marks. Python strings are
immutable.
Traversing a String- It refers to iterating through the elements of a string, one
character at a time.
Ex-
Name=”superb”
For ch in name:
Print(ch,’-‘,end=’’)
Output : s-u-p-e-r-b
String Operator-
1. Plus(+) operator- The + operator creates a new string by joining the two
operand strings e.g.
“tea”+”pot”
Teapot
2. Asterisk Operator(*) –
The * operator when used with numbers, it performs multiplication and return
the product of the two numbers operands.
Ex-
3*”go”
Gogogo
This PDF is created at https://www.pdfonline.com/convert-pdf/
Example:
name="Harsh "
surname="Gupta"
print(name+surname)
print(name*10)
ouput:
Harsh Gupta
Harsh Harsh Harsh Harsh Harsh Harsh Harsh Harsh Harsh Harsh
3. String Slices(Substring)-
It is Part of a string containing some contiguous characters from the string.
Ex-
Word=”amazing”
Word[0:7]-> amazing
Word[0:3]-> ama
Word[0:5]-> azi
Word[-5:-1] : azin
Word[:7] : amazing
Chapter 8
List Manipulation
Python Collections (Arrays)
There are four collection data types in the Python programming language:
∑ List is a collection which is ordered and changeable. Allows duplicate
members.
∑ Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
∑ Set is a collection which is unordered and unindexed. No duplicate
members.
∑ Dictionary is a collection which is unordered, changeable and indexed.
No duplicate members.
When choosing a collection type, it is useful to understand the properties of
that type. Choosing the right type for a particular data set could mean
retention of meaning, and, it could mean an increase in efficiency or security.
This PDF is created at https://www.pdfonline.com/convert-pdf/
List
A list is a collection which is ordered and changeable. In Python lists are
written with square brackets.
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Output:
["apple", "banana", "cherry"]
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
OutPut:
banana
Negative Indexing
Negative indexing means beginning 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:
This PDF is created at https://www.pdfonline.com/convert-pdf/
"cherry"
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])
print(thislist[2:])
print(thislist[:4])
OutPut:
Note: The search will start at index 2 (included) and end at index 5 (not
included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to "orange":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
OutPut:
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
OutPut:
This PDF is created at https://www.pdfonline.com/convert-pdf/
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 index -4 (included) to index -1
(excluded)
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
OutPut:
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:
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:
This PDF is created at https://www.pdfonline.com/convert-pdf/
apple
banana
cherry
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:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
print("you can eat now")
else:
print("sorry this item is not available")
print("you have to buy")
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:
This PDF is created at https://www.pdfonline.com/convert-pdf/
3
Output:
thislist = ["apple", "banana", "cherry","abcd"]
print(len(thislist[0]),len(thislist[1]))
Add 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"]
thislist.append("orange")
print(thislist)
OutPut:
['apple', 'banana', 'cherry', 'orange']
To add an item at the specified index, use the insert() method:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(0, "orange")
print(thislist)
OutPut:
['orange', 'apple', 'banana', 'cherry']
Remove Item
There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
This PDF is created at https://www.pdfonline.com/convert-pdf/
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
or
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
thislist.append("banana")
print(thislist)
OutPut:
['apple', 'cherry', 'banana']
Example
The pop() method removes the specified index, (or the last item if index is
not specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
OutPut:
Example
The del keyword removes the specified index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
OutPut:
Example
The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist
OutPut:
Example
The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
OutPut:
This PDF is created at https://www.pdfonline.com/convert-pdf/
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only
be a reference to list1, and changes made in list1 will automatically also be
made in list2.
There are ways to make a copy, one way is to use the built-in List
method copy().
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
OutPut:
Another way to make a copy is to use the built-in method list().
Example
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
OutPut:
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
This PDF is created at https://www.pdfonline.com/convert-pdf/
OutPut:
['a', 'b', 'c', 1, 2, 3]
Another way to join two lists are by appending all the items from list2 into
list1, one by one:
thislist = ["apple", "banana", "cherry"]
mylist=["one","two"]
mylist=mylist[1]+thislist[1]
print(mylist)
output:
twobanana
Example
Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
OutPut:
Or you can use the extend() method, which purpose is to add elements from
one list to another list:
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
OutPut:
['a', 'b', 'c', 1, 2, 3]
This PDF is created at https://www.pdfonline.com/convert-pdf/
The list() Constructor
It is also possible to use the list() constructor to make 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:
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
Find out?
This PDF is created at https://www.pdfonline.com/convert-pdf/
Example:
list1 = [1, 1, 1, 2, 3, 2, 1]
# Counts the number of times 1 appears in list1
print(list1.count(1))
list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b']
# Counts the number of times 'b' appears in list2
print(list2.count('b'))
list3 = ['Cat', 'Bat', 'Sat', 'Cat', 'cat', 'Mat']
# Counts the number of times 'Cat' appears in list3
print(list3.count('Cat'))
output:
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value
Find out?
Example:
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
This PDF is created at https://www.pdfonline.com/convert-pdf/
# Will print the index of '4' in list1
print(list1.index(4))
list2 = ['cat', 'bat', 'mat', 'cat', 'pet']
# Will print the index of 'cat' in list2
print(list2.index('cat'))
output:
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
Find out?
Example:
# a list of numbers
list1 = [1, 2, 3, 4, 1, 2, 6]
This PDF is created at https://www.pdfonline.com/convert-pdf/
list1.reverse()
print(list1)
output
[6, 2, 1, 4, 3, 2, 1]
sort() Sorts the list find out?
Example:
# List of Integers
numbers = [1, 3, 4, 2]
# Sorting list of Integers
numbers.sort()
print(numbers)
output:
[1, 2, 3, 4]
Reserve order:
numbers = ['ajay', 'babloo', 'akash', 'vikas']
l1=[1,4,6,3,2]
numbers.sort(reverse=True)
l1.sort(reverse=False)
print(numbers)
print(l1)
This PDF is created at https://www.pdfonline.com/convert-pdf/
Chapter 9
Dictionaries
Python offers many different ways to organize collections of
data items, such as strings, lists, dictionaries, tuples etc.
Dictionary –key:values pairs->
Dictionaries are mutable, unordered collections with elements
in the form of a key:value pairs that associate keys to values.
Creating a dictionary-
<dictionary-name>={key:value,key:value}
>>>teachers={“dimple”:”computer
science”,”Karen”:”sociology”}
>>>teachers
{“dimple”:”computer science”,”Karen”:”sociologh”}
>>> teachers[“dimple”]
Computer science
Traversing a dictionary-
For <item> in <Dictionary>:
Process each items
Ex-
D1={5:”number”,”a”:”string”}
for key in D1:
print(key,"is having value",D1[key])
Accessing keys or value simultaneously –
>>>d.keys()
>>>d.values()
>>>list(d.keys())
This PDF is created at https://www.pdfonline.com/convert-pdf/
>>>list(d.values())
Characteristics of a dictionary
1. Unordered set
2. Not a sequence
3. Keys must be unique
4. Mutable
5. Indexed by keys not numbers.
Working with Dictionary-
1. Initializing a dictionary-
>>>emp={‘name’:’john’,’salary’:10000,’age’:24}
>>> emp[‘age’]=32
>>>emp
{‘name’:’john’,’salary’:10000,’age’:32}
2. Adding new element in the dictionary-
Emp[‘address’]=”Bhopal”
>>>emp
{‘name’:’john’,’salary’:10000,’age’:24,’address’:’bhopal’}
3. Updating existing element-
>>> emp[‘salary’]=30000
>>>emp
{‘name’:’john’,’salary’:30000,’age’:24,’address’:’bhopal’}
4. Deleting Element from a dictionary –
>>>Del emp[‘age’]
>>> emp.pop[‘address’]
del D1 – to remove complete disctionary
https://cs231n.github.io/python-numpy-tutorial/#arrays
This PDF is created at https://www.pdfonline.com/convert-pdf/