0% found this document useful (0 votes)
2 views127 pages

01 Python I

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

01 Python I

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

PYTHON - I

Credits
 [Link]
 Machine learning: an algorithmic perspective. 2nd Edition, Marsland,
Stephen. CRC press, 2015. Appendix A.
 [Link]
 [Link]
 [Link]
module-in-python
 Python is a general-purpose interpreted, interactive, object-oriented,
and high-level programming language.
 Portable

 Extendable

 Databases

 GUI Programming
Hello World Program
print("Hello, World!")
Python Identifiers
 Used to identify a variable, function, class, module or other object
 An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).
Lines and Indentations
 Python does not use braces({}) to indicate blocks of code for class and
function definitions or flow control.
 Blocks of code are denoted by line indentation, which is rigidly
enforced.
if True:
print ("True")
else:
print ("False")
print("Hello")
 The following gives error
if True:
print ("True")
else:
print ("False")
print("Hello")
Comments
# First comment
print ("Hello, Python!") # second comment
Variable Declaration
# declaration/creation of variables happen automatically
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print(counter)
print(miles)
print(name)
Data Types
Standard Data Types
 Numbers
 String
 List
 Tuple
 Dictionary
 A complex number consists of an ordered pair of real floating-point
numbers denoted by x + yj, where x and y are real numbers and j is
the imaginary unit.
Strings
 Python accepts single ('), double (") and triple (''' or """) quotes to denote
string literals, as long as the same type of quote starts and ends the string.
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
print(word)
print(sentence)
print(paragraph)
print('a' + 'd')
ad
print("hello"+" world")
hello world
Lists
 A list contains items separated by commas and enclosed within square
brackets ([]).
 Similar to arrays in C. However, items belonging to a list can be of
different data type.

mylist = [0, 3, 2, 'hi']


print(mylist)
[0, 3, 2, 'hi']
newlist = [3, 2, [5, 4, 3], [2, 3, 2]]
print(newlist)
[3, 2, [5, 4, 3], [2, 3, 2]]
#list within list

print(newlist[0])
3
#indexing starts at 0
#returns element from the last
newlist = [3, 2, [5, 4, 3], [2, 3, 2]]
print(newlist[-1])
[2, 3, 2]

print(newlist[-2])
[5, 4, 3]
print(newlist[3][1])
3
Slice operator ‘:’
newlist = [3, 2, [5, 4, 3], [2, 3, 2]]
print(newlist[2:4])
[[5, 4, 3], [2, 3, 2]]
#inclusive of start index and exclusive of end index

print(newlist[0:4:2])
[3, [5, 4, 3]]
#behaves as [start:stop:step]
newlist = [3, 2, [5, 4, 3], [2, 3, 2]]
print(newlist[::-1])
[[2, 3, 2], [5, 4, 3], 2, 3]
#reverses the elements of the list

print(newlist[:3])
[3, 2, [5, 4, 3]]
print(newlist[1:])
[2, [5, 4, 3], [2, 3, 2]]
mylist = [3, 2, [5, 4, 3], [2, 3, 2]]
alist = mylist #does shallow copy
alist[0]=4
print(mylist)
[4, 2, [5, 4, 3], [2, 3, 2]]

alist = mylist[:] #does deep copy only to one level


alist[0]=5
print(mylist)#OK
[4, 2, [5, 4, 3], [2, 3, 2]]

#However
alist[2][0]=1
print(mylist)
[4, 2, [1, 4, 3], [2, 3, 2]]
Deep Copy
import copy
mylist = [3, 2, [5, 4, 3], [2, 3, 2]]
alist = [Link](mylist)
alist[0]=5
alist[2][0]=2
print(mylist)
print(alist)
[3, 2, [5, 4, 3], [2, 3, 2]]
[5, 2, [2, 4, 3], [2, 3, 2]]
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (tinylist * 2) # Prints list two times
[123, 'john', 123, 'john']
print (list + tinylist) # Prints concatenated lists
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Comparing Lists
a==b
Compares lists item wise, returns TRUE if elements and their count is the same;
returns FALSE otherwise

a =[3, 2, 4, 1]
b= [3, 2, 4, 1]
print(a==b)
True

c = [3,2,4,1,0]
print(a==c)
False
Tuple
 A tuple is an immutable list, meaning that it is read-only and doesn’t
change.
 Tuples are defined using round brackets

mytuple = (0, 3, 2, 'h')


tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
('abcd', 786, 2.23, 'john', 70.2)
print (tuple[0]) # Prints first element of the tuple
abcd
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
(786, 2.23)
print (tuple[2:]) # Prints elements starting from 3rd element
(2.23, 'john', 70.2)
print (tinytuple * 2) # Prints tuple two times
(123, 'john', 123, 'john')
print (tuple + tinytuple) # Prints concatenated tuple
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Tuples are read-only
 The following gives error while running the code
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
#The next sentence gives error while running the code
list[2] = 1000 # Valid syntax with list
Dictionaries
 Kind of hash-table type
 Consist of key-value pairs
 Dictionaries are enclosed in curly braces
 You assign a key to each entry that you can use to access it
months = {'Jan': 31, 'Feb': 28, 'Mar': 31}
print(months['Jan'])
31
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
This is one
This is oneprint (dict[2]) # Prints value for 2 key
This is two
print (tinydict) # Prints complete dictionary
{'dept': 'sales', 'code': 6734, 'name': 'john'}
print ([Link]()) # Prints all the keys
dict_keys(['dept', 'code', 'name'])
print ([Link]()) # Prints all the values
dict_values(['sales', 6734, 'john'])
Data Type Conversion
 To convert between types, you simply use the type-name as a function.
print(int(2.7))
2
print(float(2))
2.0
print(complex(2,4))
(2+4j)
print(str(44+55)+str(30/9))
993.3333333333333335
Basic Operators
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Arithmetic Operators
b=21
Assume
a=10 and
1. a = 21; b = 10; c = 0 10. c=a%b
2. c=a+b 11. print ("Line 5 - Value of c is ", c)
3. print ("Line 1 - Value of c is ", c) Line 5 - Value of c is 1
Line 1 - Value of c is 31 12. a=2
4. c=a-b 13. b=3
5. print ("Line 2 - Value of c is ", c ) 14. c = a**b
Line 2 - Value of c is 11 15. print ("Line 6 - Value of c is ", c)
6. c=a*b Line 6 - Value of c is 8
7. print ("Line 3 - Value of c is ", c) 16. a = 10
Line 3 - Value of c is 210 17. b=5
8. c=a/b 18. c = a//b
9. print ("Line 4 - Value of c is ", c ) 19. print ("Line 7 - Value of c is ", c)
Line 4 - Value of c is 2.1 Line 7 - Value of c is 2
Comparison Operators
b=20
Assume
a=10 and
1. a = 21; b = 10 10. if ( a < b ):
2. if ( a == b ): 11. print ("Line 3 - a is less than b" )
3. print ("Line 1 - a is equal to b") 12. else:
4. else: 13. print ("Line 3 - a is not less than
5. print ("Line 1 - a is not equal to b")
b") Line 3 - a is not less than b
Line 1 - a is not equal to b 14. if ( a > b ):
6. if ( a != b ): 15. print ("Line 4 - a is greater than
7. print ("Line 2 - a is not equal to b")
b") 16. else:
8. else: 17. print ("Line 4 - a is not greater
9. print ("Line 2 - a is equal to b") than b")
Line 2 - a is not equal to b Line 4 - a is greater than b
1. a = 21; b = 10 8. print ("Line 6 - b is either
2. a,b=b,a #values of a and b greater than or equal to b")
swapped. a becomes 10, b 9. else:
becomes 21 10. print ("Line 6 - b is neither
3. if ( a <= b ): greater than nor equal to b")
4. print ("Line 5 - a is either less Line 6 - b is either greater than or equal to
b
than or equal to b")
5. else:
6. print ("Line 5 - a is neither less
than nor equal to b")
Line 5 - a is either less than or equal to b

7. if ( b >= a ):
x=4
print(3<x<6)
True
# not equal to test is != or <>
Assignment Operator
Assignment Operator (II)
1. a = 21 11. print ("Line 4 - Value of c is ", c )
2. b = 10 Line 4 - Value of c is 52.0
3. c=0 12. c=2
4. c=a+b 13. c %= a
5. print ("Line 1 - Value of c is ", c) 14. print ("Line 5 - Value of c is ", c)
Line 1 - Value of c is 31 Line 5 - Value of c is 2
6. c += a 15. c **= a
7. print ("Line 2 - Value of c is ", c ) 16. print ("Line 6 - Value of c is ", c)
Line 2 - Value of c is 52 Line 6 - Value of c is 2097152
8. c *= a 17. c //= a
9. print ("Line 3 - Value of c is ", c ) 18. print ("Line 7 - Value of c is ", c)
Line 3 - Value of c is 1092 Line 7 - Value of c is 99864
10. c /= a
Assume
a=10 and
b=20
Bitwise Operators
1. a = 60 # 60 = 0011 1100 c,':',bin(c))
2. b = 13 # 13 = 0000 1101 result of EXOR is 49 : 0b110001
3. print 11. c = ~a; # -61 = 1100 0011
('a=',a,':',bin(a),'b=',b,':',bin(b)) 12. print ("result of COMPLEMENT is ",
a= 60 : 0b111100 b= 13 : 0b1101 c,':',bin(c))
4. c=0 result of COMPLEMENT is -61 : -0b111101
5. c = a & b; # 12 = 0000 1100 13. c = a << 2; # 240 = 1111 0000

6. print ("result of AND is ", c,':',bin(c)) 14. print ("result of LEFT SHIFT is ",
result of AND is 12 : 0b1100 c,':',bin(c))
result of LEFT SHIFT is 240 : 0b11110000
7. c = a | b; # 61 = 0011 1101
8. print ("result of OR is ", c,':',bin(c)) 15. c = a >> 2; # 15 = 0000 1111
result of OR is 61 : 0b111101 16. print ("result of RIGHT SHIFT is ",
9. c = a ^ b; # 49 = 0011 0001 c,':',bin(c))
result of RIGHT SHIFT is 15 : 0b1111
10. print ("result of EXOR is ",
Logical Operators
x=5
y=2
print((x>4) and (y<3))
True

print((x>5) or (y<3))
True

print(not(x>5) and (y<3))


True
Membership Operators
 Test for membership in a sequence, such as strings, lists, or tuples.
1. a = 10 10. else:

2. b = 20 11. print ("Line 2 - b is available in


3. list = [1, 2, 3, 4, 5 ] the given list")
4. if ( a in list ): Line 2 - b is not available in the given list
12. c=b/a
5. print ("Line 1 - a is available in
the given list") 13. if ( c in list ):

6. else: 14. print ("Line 3 - a is available in


7. print ("Line 1 - a is not the given list")
available in the given list") 15. else:

Line 1 - a is not available in the given list 16. print ("Line 3 - a is not
8. if ( b not in list ): available in the given list")
9. print ("Line 2 - b is not Line 3 - a is available in the given list
available in the given list")
Identity Operators
 Compare the memory locations of two objects.
1. a = 20 10. else:
2. b = 20 11. print ("Line 3 - a and b do not
3. print ('Line 1','a=',a,':',id(a), have same identity")
'b=',b,':',id(b)) Line 3 - a and b have same identity
Line 1 a= 20 : 497419344 b= 20 : 12. b = 30
497419344 13. print ('Line 4','a=',a,':',id(a),
4. if ( a is b ): 'b=',b,':',id(b))
5. print ("Line 2 - a and b have Line 4 a= 20 : 497419344 b= 30 :
same identity") 497419664
6. else: 14. if ( a is not b ):
7. print ("Line 2 - a and b do not 15. print ("Line 5 - a and b do not
have same identity") have same identity")
Line 2 - a and b have same identity 16. else:
8. if ( id(a) == id(b) ): 17. print ("Line 5 - a and b have
9. print ("Line 3 - a and b have same identity")
same identity") Line 5 - a and b do not have same identity
Python Operator Precedence
Highest
Lowest
1. a = 20 9. print ("Value of ((a + b) * c) / d
2. b = 10 is ", e)
3. c = 15 Value of (a + b) * (c / d) is 90.0

4. d=5 10. e = (a + b) * (c / d) # (30) *


(15/5)
5. print ("a:%d b:%d c:%d d:%d"
% (a,b,c,d )) 11. print ("Value of (a + b) * (c / d)
a:20 b:10 c:15 d:5
is ", e)
Value of (a + b) * (c / d) is 90.0
6. e = (a + b) * c / d #( 30 * 15 )
/5 12. e = a + (b * c) / d # 20 +
(150/5)
7. print ("Value of (a + b) * c / d is
", e) 13. print ("Value of a + (b * c) / d is
Value of (a + b) * c / d is 90.0
", e)
Value of a + (b * c) / d is 50.0
8. e = ((a + b) * c) / d # (30 * 15 )
/5
Decision Making
if statement
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")
1 - Got a true expression value
100
Good bye!
if else statement
amount=int(input("Enter amount: ")) Output:
if amount<1000: Enter amount: 300
discount=amount*0.05 Discount 15.0
print ("Discount",discount) Net payable: 285.0
else:
discount=amount*0.10
print ("Discount",discount)
print ("Net payable:",amount-discount)
elif statement (Just like ‘else if’ in C/C++)
amount=int(input("Enter amount: ")) Output 1:
if amount<1000:
Enter amount: 600
discount=amount*0.05
print ("Discount",discount) Discount 30.0
elif amount<5000: Net payable: 570.0
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
elif statement (Just like ‘else if’ in C/C++)
amount=int(input("Enter amount: ")) Output 2:
if amount<1000:
Enter amount: 3000
discount=amount*0.05
print ("Discount",discount) Discount 300.0
elif amount<5000: Net payable: 2700.0
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
elif statement (Just like ‘else if’ in C/C++)
amount=int(input("Enter amount: ")) Output 3:
if amount<1000:
Enter amount: 6000
discount=amount*0.05
print ("Discount",discount) Discount 900.0
elif amount<5000: Net payable: 5100.0
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
Reading Input
 The input([prompt]) function reads one line from standard input and
returns it as a string (removing the trailing newline).

str = input("Enter your input: ");


print("Received input is : ", str)
Looping Constructs
while loop
count = 0 Output:
The count is: 0
while (count < 9):
The count is: 1
print ('The count is:', count) The count is: 2
count = count + 1 The count is: 3
print ("Good bye!") The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Using else with while loop
 If the else statement is used with a Output:
while loop, the else statement is 0 is less than 5
executed when the condition
becomes false. 1 is less than 5
count = 0 2 is less than 5
while count < 5: 3 is less than 5
print (count, " is less than 5") 4 is less than 5
count = count + 1 5 is not less than 5
else:
print (count, " is not less than 5")
range() function
 range(n) generates an iterator to progress integers starting with 0
upto n-1.
print(range(0, 5))
range(0, 5)
 To obtain a list object of the sequence, it is type casted to list().

Now this list can be iterated using the for statement.


print(list(range(5)))
[0, 1, 2, 3, 4]
for loop
for var in list(range(5)): Output:
print (var) 0
1
2
3
4
for loop
1. for letter in 'Python': # traversal of Output:
Current Letter : P
a string sequence
Current Letter : y
2. print ('Current Letter :', letter) Current Letter : t
3. print()#prints newline character Current Letter : h
Current Letter : o
4. fruits = ['banana', 'apple', 'mango'] Current Letter : n
5. for fruit in fruits: # traversal of List
sequence Current fruit : banana
Current fruit : apple
6. print ('Current fruit :', fruit) Current fruit : mango
7. print ("Good bye!") Good bye!
for loop iteration by sequence index
for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter)
print()#prints newline character
Output
fruits = ['banana', 'apple', 'mango']
Current fruit : banana
for fruit in fruits: # traversal of List sequence
Current fruit : apple
print ('Current fruit :', fruit)
Current fruit : mango
print ("Good bye!")
Good bye!
Else statement with Loops
 If the else statement is used with a for loop, the else block is executed
only if for loops terminates normally (and not by encountering break
statement).
 If the else statement is used with a while loop, the else statement is
executed when the condition becomes false.
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list does not contain even number')

the list does not contain even number


Loop Control Statements
break statement
1. for letter in 'Python': # First Example Output:
2. if letter == 'h':
Current Letter : P
3. break
4. print ('Current Letter :', letter) Current Letter : y
Current Letter : t
5. var = 10 # Second Example
Current variable value : 10
6. while var > 0:
7. print ('Current variable value :', var) Current variable value : 9
8. var = var -1 Current variable value : 8
9. if var == 5: Current variable value : 7
10. break
Current variable value : 6
11. print ("Good bye!") Good bye!
Output:
Current Letter : P
continue statement Current Letter : y
Current Letter : t
1. for letter in 'Python': # First Example Current Letter : o
2. if letter == 'h': Current Letter : n
3. continue Current variable value : 9
4. print ('Current Letter :', letter)
Current variable value : 8
Current variable value : 7
5. var = 10 # Second Example
Current variable value : 6
6. while var > 0:
7. var = var -1 Current variable value : 4
8. if var == 5: Current variable value : 3
9. continue Current variable value : 2
10. print ('Current variable value :', var) Current variable value : 1
Current variable value : 0
11. print ("Good bye!") Good bye!
Working with Lists
Lists
 A list contains items separated by commas and enclosed within square
brackets ([]).
 Similar to arrays in C. However, items belonging to a list can be of
different data type.

mylist = [0, 3, 2, 'hi']


print(mylist)
[0, 3, 2, 'hi']
Accessing Values in Lists
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])#through indexing
list1[0]: physics

print ("list2[1:5]: ", list2[1:5])#using slicing


list2[1:5]: [2, 3, 4, 5]
Lists – updating single element
list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : ", list[2])
Value available at index 2 : 1997

list[2] = 2001
print ("New value available at index 2 : ", list[2])
New value available at index 2 : 2001
Lists – updating multiple elements using “:”
oddList = [0,2,4,6]
evenList = [1,3,5,7]
newList = [9,9,9,9,9,9,9,9]
print(newList)
[9, 9, 9, 9, 9, 9, 9, 9]

newList[::2]=oddList
newList[1::2]=evenList
print(newList)
[0, 1, 2, 3, 4, 5, 6, 7]
List: deleting an element using del
list = ['physics', 'chemistry', 1997, 2000]
print (list)
['physics', 'chemistry', 1997, 2000]

del list[2]
print ("After deleting value at index 2 : ", list)
After deleting value at index 2 : ['physics', 'chemistry', 2000]
Basic List Operations
Indexing and Slicing
Built-in List Functions
List len() Method
 len() method returns the number of elements in the list.
 Syntax
methodlen(list)
 Parameters
 list - This is a list for which, number of elements are to be counted.
 Return Value
This method returns the number of elements in the list.
list1 = ['physics', 'chemistry', 'maths']
print (len(list1))
3

list2=list(range(5)) #creates list of numbers between 0-4


print (len(list2))
5
List max() Method
 max() method returns the elements from the list with maximum value.
 Syntax
max(list)
 Parameters
 list - This is a list from which max valued element are to be returned.
 Return Value
This method returns the elements from the list with maximum value.
list1, list2 = ['C++','Java', 'Python'],
[456, 700, 200]
print ("Max value element : ", max(list1))
Max value element : Python

print ("Max value element : ", max(list2))


Max value element : 700
List min() Method
 min() returns the elements from the list with minimum value.
 Syntax
min(list)
 Parameters
 list - This is a list from which min valued element is to be returned.
 Return Value:
This method returns the elements from the list with minimum value.
list1, list2 = ['C++','Java', 'Python'],
[456, 700, 200]
print ("min value element : ", min(list1))
min value element : C++

print ("min value element : ", min(list2))


min value element : 200
List list() Method
 list() method takes sequence types and converts them to lists. This is
used to convert a given tuple into list.
 Syntax
list(seq )
 Parameters
 seq - This is a tuple or string to be converted into list.
 Return Value
This method returns the list.
aTuple = (123, 'C++', 'Java', 'Python')
list1 = list(aTuple)
print ("List elements : ", list1)
List elements : [123, 'C++', 'Java', 'Python']

str="Hello World"
list2=list(str)#converts string to a list
print ("List elements : ", list2)
List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
list Methods
 [Link](obj): Appends object obj to list
 [Link](obj): Returns count of how many times obj occurs in list
 [Link](seq): Appends the contents of seq to list
 [Link](obj): Returns the lowest index in list that obj appears
 [Link](index, obj): Inserts object obj into list at offset index
 [Link](obj=list[-1]): Removes and returns last object or obj from list
 [Link](obj): Removes object obj from list
 [Link](): Reverses objects of list in place
 [Link]([func]): Sorts objects of list, use compare func if given
List append() Method
 append() method appends a passed obj into the existing list.
 Syntax
append(obj)
 Parameters
 obj - This is the object to be appended in the list.
 Return Value
This method does not return any value but updates existing list.
list1 = ['C++', 'Java', 'Python']
[Link]('C#')
print ("updated list : ", list1)
updated list : ['C++', 'Java', 'Python', 'C#']
List count() Method
 count() method returns count of how many times obj occurs in list.
 Syntax
count(obj)
 Parameters
 obj - This is the object to be counted in the list.
 Return Value
This method returns count of how many times obj occurs in list.
aList = [123, 'xyz', 'zara', 'abc', 123];
print ("Count for 123 : ", [Link](123))
Count for 123 : 2

print ("Count for zara : ",


[Link]('zara'))
Count for zara : 1
List extend() Method
 extend() method appends the contents of seq to list.
 Syntax
[Link](seq)
 Parameters
 seq - This is the list of elements
 Return Value
This method does not return any value but adds the content to an existing list.
list1 = ['physics', 'chemistry', 'maths']
list2=list(range(5)) #creates list of
numbers between 0-4
[Link]( list2)
print ('Extended List :',list1)

Extended List : ['physics', 'chemistry', 'maths', 0, 1, 2, 3, 4]


List index() Method
 index() method returns the lowest index in list that obj appears.
 Syntax
index(obj)
 Parameters
 obj - This is the object to be find out.
 Return Value
This method returns index of the found object otherwise raises an exception
indicating that the value is not found.
list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry',
[Link]('chemistry'))
Index of chemistry 1

print ('Index of C#', [Link]('C#'))


Traceback (most recent call last):
print ('Index of C#', [Link]('C#'))
ValueError: 'C#' is not in list
List insert() Method
 insert() method inserts object obj into list at offset index.
 Syntax
insert(index, obj)
 Parameters
 index - This is the Index where the object obj need to be inserted.
 obj - This is the Object to be inserted into the given list.

 Return Value
This method does not return any value but it inserts the given element at the
given index.
list1 = ['physics', 'chemistry', 'maths']
[Link](1, 'Biology')
print ('Final list : ', list1)
Final list : ['physics', 'Biology', 'chemistry', 'maths']
List pop() Method
 pop() method removes and returns last object or obj from the list.
 Syntax
pop(obj=list[-1])
 Parameters
 obj - This is an optional parameter, index of the object to be removed from
the list.
 Return Value
This method returns the removed object from the list.
list1 = ['physics', 'Biology', 'chemistry',
'maths']
[Link]()
print ("list now : ", list1)
list now : ['physics', 'Biology', 'chemistry']

[Link](1)
print ("list now : ", list1)
list now : ['physics', 'chemistry']
List remove() Method
 remove() removes given obj from the list
 Syntax
remove(obj)
 Parameters
 obj - This is the object to be removed from the list.
 Return Value
 This method does not return any value but removes the given object from the
list
list1 = ['physics', 'Biology', 'chemistry',
'maths']
[Link]('Biology')
list now : ['physics', 'chemistry', 'maths']

print ("list now : ", list1)


[Link]('maths')
print ("list now : ", list1)
list now : ['physics', 'chemistry']
List reverse() Method
 reverse() method reverses objects of list in place.
 Syntax
reverse()
 Parameters
NA
 Return Value
This method does not return any value but reverse the given object from the
list.
list1 = ['physics', 'Biology', 'chemistry',
'maths']
[Link]()
print ("list now : ", list1)
list now : ['maths', 'chemistry', 'Biology', 'physics']
List sort() Method
 sort() method sorts objects of list, use compare function if given.
 Syntax
sort([func])
 Parameters
NA
 Return Value
This method does not return any value but reverses the given object from the
list.
list1 = ['physics', 'Biology', 'chemistry',
'maths']
[Link]()
print ("list now : ", list1)
list now : ['Biology', 'chemistry', 'maths', 'physics']
Importing Modules
Writing and Importing Code
 Python is a scripting language
 everything can be run interactively from the command line
 .py extension for source file; complied into .pyc file when first loaded
 Any set of commands or functions is known as a module in Python
 To load it, you use the import command
 If you import a script file then Python will run it immediately, but if it is a set
of functions then it will not run anything.
def print_func( par ):
print("Hello : ", par)
return
The above can be saved as “[Link]”
import support
support.print_func("Zara")
Hello : Zara
To add a folder in the list of folders to search while importing a module
import sys
[Link]("./otherDir")
import support
support.print_func("Zara")
Hello : Zara
Random Library
random: Generate pseudo-random numbers
 This module implements pseudo-random number generators for various
distributions.
 When to use it?
 We want the computer to pick a random number in a given range
 Pick a random element from a list, pick a random card from a deck, flip a
coin etc.
 Shuffling a list of numbers of data samples

 Need to import random module


choice()
 choice() method returns a random item from a list, tuple, or string.
 Syntax
[Link](seq )
 Parameters
 seq - This could be a list, tuple, or string...
 Return Value
This method returns a random item.
import random

outcomes = { 'heads':0,
'tails':0,
}
sides = list([Link]())

for i in range(10000):
outcomes[ [Link](sides) ] += 1

print('Heads:', outcomes['heads'])
print('Tails:', outcomes['tails'])
Heads: 5033
Tails: 4967
randrange()
 randrange() method returns a randomly selected element from
range(start, stop, step).
 Syntax
randrange ([start,] stop [,step])
 Parameters
 start - Start point of the range. This would be included in the range. Default
is 0.
 stop - Stop point of the range. This would be excluded from the range.
 step - Value with which number is incremented. Default is 1.

 Return Value
This method returns a random item from the given range.
import random
# randomly select an odd number between 1-100
print ("randrange(1,100, 2) : ",
[Link](1, 100, 2))
randrange(1,100, 2) : 85

# randomly select a number between 0-99


print ("randrange(100) : ",
[Link](100))
randrange(100) : 97
random()
 random() method returns a random floating point number in the range
[0.0, 1.0].
 Syntax
random( )
 Parameters
NA
 Return Value
This method returns a random float r, such that 0.0 <= r <= 1.0
import random
# First random number
print ("random() : ", [Link]())
random() : 0.5476053663383964

# Second random number


print ("random() : ", [Link]())
random() : 0.1308558535179697
seed() method
 Initializes the basic random number generator.
 Call this function before calling any other random module function.
 Syntax
([x], [y])
 Parameters
x - This is the seed for the next random number. If omitted, then it takes
system time to generate the next random number.
 Y - This is version number (default is 2). str, byte or byte array object gets
converted in int. Version 1 used hash() of x.
import random
[Link]()
print ("random number with default seed",
[Link]())
random number with default seed 0.3844734828760715

[Link](10)
print ("random number with int seed", [Link]())
random number with int seed 0.5714025946899135

[Link]("hello",2)
print ("random number with string seed",
[Link]())
random number with string seed 0.3537754404730722
shuffle()
 shuffle() method randomizes the items of a list in place.
 Syntax
shuffle (lst,[random])
 Parameters
 lst- This could be a list or tuple.
 random - This is an optional 0 argument function returning float between 0.0
-1.0.
 Return Value
This method returns reshuffled list.
import random
list = [20, 16, 10, 5];
[Link](list)
print ("Reshuffled list : ", list)
Reshuffled list : [5, 16, 10, 20]

[Link](list)
print ("Reshuffled list : ", list)
Reshuffled list : [20, 10, 5, 16]
uniform()
 uniform() method returns a random float r, such that x is less than or
equal to r and r is less than y.
 Syntax
uniform(x, y)
 Parameters
x - Sets the lower limit of the random float.
 y - Sets the upper limit of the random float.

 Return Value
This method returns a floating point number r such that x <=r < y.
import random
print ("Random Float uniform(5, 10) : ",
[Link](5, 10))
Random Float uniform(5, 10) : 9.481444778178155

print ("Random Float uniform(7, 14) : ",


[Link](7, 14))
Random Float uniform(7, 14) : 12.678404498161704
 It also has functions for generating popular distributions like beta,
exponential, gamma, Gaussian (normal), Pareto and Weibull
distribution.
 For details see [Link]

You might also like