Python Module 3
Python Module 3
• If you want to represent a group of individual objects as a single entity then we use
list.
• The list elements will be placed within square brackets and with comma operator.
Ex:
a=[34,22,65,11]
type(a)
<class ‘list’>
• Insertion order is preserved.
print(a)
[34,22,65,11]
• Duplicate objects are allowed.
a.append(22)
print(a)
[34,22,65,11,22]
• Heterogeneous objects are allowed.
a.append('python')
print(a)
[34,22,65,11,22,'python']
• List is dynamic, based on our requirement we can increase the size or decrease the
size.
• It allows both positive and negative indexes. +ve index means from left to right where
as negative index means right to left.
Ex:
0 1 2 3 4
l=[10,20,30,40,10]
-5 -4 -3 -2 -1
• List objects are mutable, i.e we can change the content.
Accessing elements of List
• We can access elements of the list either by using index or by using slice operator.
• By using index:
Ex:
a=[45,12,53,26]
print(a[0]) #45
print(a[-1]) #26
print(a[10]) #IndexError
Ex:
n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2])
print(n[4::2])
print(n[3:7])
print(n[8:2:-2])
print(n[4:100])
output:
[3,5,7]
[5,7,9]
[4,5,6,7]
[9,7,5]
[5,6,7,8,9,10]
List Functions: -
len(): - Returns the number of elements in the list.
Ex:
a=[23,42,66,23,57]
print("Length of the list=",len(a))
index(element): - Returns the index of first occurrence of the specified element. If element
is not found it displays ValueError.
Ex:
a=[23,54,65,23,65,34,23,77]
print(a.index(65))
insert(): -
This function is used to add element at specified position.
If index is greater than the length of the list then the element will be inserted at last position.
If index is less than the highest negative index of list then the element will be inserted at first
position.
Ex:
a=[23,87,33,54]
print(a)
a.insert(3,55)
print(a)
a.insert(23,65)
print(a)
a.insert(-10,5)
print(a)
pop(): - To remove last element from the list and it returns that element. If list is empty then
it displays IndexError.
Ex:
l=[10,20,30,40]
print(l)
print(l.pop())
print(l)
sort(): - This function is used to sort the elements. By default it is ascending order.
Ex:
l=[50,20,40,25]
print(l)
l.sort()
print(l)
→The problem in this approach is by using one reference variable if we are changing
content, then those changes will be reflected to the other reference variable.
→To overcome this problem we should go for cloning.
→The process of creating exactly duplicate independent object is called cloning.
→We can implement cloning by using slice operator or by using copy() method.
Ex:
l1=[1,2,3]
l2=[4,5,6]
l3 = l1+l2
print(l3)
Nested lists
Sometimes we can take one list inside another list. Such type of lists are called nested lists.
Ex:
n=[0,1,2,[10,20,30]]
print(n[0]) #0
print(n[3]) #[10,20,30]
print(n[3][0]) #10
Note: We can access nested list elements by using index just like accessing multi
dimensional array elements.
List comprehensions:
It is very easy and compact way of creating list objects from any iterable objects
based on some condition.
Syntax:
list=[expression for item in list if condition]
Ex:
s=[x*x for x in range(1,11)]
print(s)
v=[2**x for x in range(1,6)]
print(v)
m=[x for x in s if x%2==0]
print(m)
Tuple:
→Tuple is exactly same as list except that it is immutable, that is once we create tuple object
then we cannot perform any changes in that object. Hence, tuple is read only version of list.
→If our data is fixed and never changes then we should go for tuple.
→Insertion order is preserved.
→Duplicates are allowed.
→Heterogeneous objects are allowed.
→Tuple supports both positive and negative index.
→We can represent tuple elements within () with comma operator.
→Parentheses are optional but recommended to use.
Ex:
t=10,20,30,40
print(t)
print(type(t))
Note: We have to special care about single valued tuple. Compulsory the value should ends
with comma, otherwise it is not treated as tuple.
Ex:
t=(10)
print(t)
print(type(t))
Ex:
t=(10,)
print(t)
print(type(t))
By using index:
t=(10,20,30,40)
print(t[3])
print(t[-2])
By using slice:
t=(10,20,30,40,45,33,22)
print(t[2:5])
print(t[2:100])
print(t[::5])
Tuple vs immutability
→Once we create tuple, we cannot change its contet.
→Hence tuple objects are immutable.
Ex:
t=(10,20,30,60)
t[1]=45 #TypeError: ‘tuple’ object does not support items assignment
index(element): - Returns index of first occurrence of the given element. If the element is
not available then we will get ValueError.
Ex:
t=(10,20,10,10,20)
print(t.index(10)) #0
print(t.index(30)) #ValueError: tuple.index(x): x not in tuple.
Un-Packing:
Splitting a tuple into individual elements.
Ex:
t=(13,20,35,44)
a,b,c,d=t
print("a={} b={} c={} d={}".format(a,b,c,d))
Note: At the time of tuple unpacking the number of variables and number of values should
be same, otherwise we will get ValueError.
Note:
→While creating empty set we have to take special care.
→Compulsory we should use set() function.
→s={} →It treated as dictionary.
Ex:
s={}
print(s)
print(type(s))
Ex:
s=set()
print(s)
print(type(s))
Set functions:
s.add(element): - To add element to the set.
Ex:
s={10,20,30}
s.add(40)
print(s)
s.update(sequence): - To add multiple items to the set. Arguments are not individual
elements and these are iterable objects like List, Range …
Ex:
s={10,20,30,40}
l=[50,60,70]
s.update(l)
print(s)
pop(): - To remove and return the some random element (based on hash code). If set is
empty then it displays KeyError
Ex:
s={10,20,30,40}
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
discard(element): - To remove the specified element. If element is not found then it does
not display any error message.
Ex:
s={10,20,30,40}
s.discard(40)
print(s)
s.discard(140)
Mathematical operations:
set1.union(set2): - Returns a union of two sets. Using the ‘|’ operator between two sets is
the same as writing set1.union(set2).
set1.union(set2) or set1|set2
Ex:
s1={10,20,30,40}
s2={30,40,50,60}
print(s1.union(s2))
print(s1|s2)
set1.difference(set2): - Returns a set containing all the elements of invoking set but not of
the second set. Using the ‘-’ operator between two sets is the same as writing
set1.difference(set2).
set1.difference(set2) or set1-set2
Ex:
s1={10,20,30,40}
s2={30,40,50,60}
print(s1.difference(s2))
print(s1-s2)
Creating dictionary:
Empty dict:
d={}
#d=dict()
d[100]='satish'
d[103]='lokesh'
d[104]='rajesh'
print(type(d))
print(d)
Dictionary functions:
len(): Returns the number of items in the dictionary.
clear(): - To remove all entries from the dictionary.
del: - To remove dictionary.
Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
del d
print(d)
get(key): - It returns the value of the given key. If key is not found, it returns
None.
Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
print(d.get(103))
print(d.get(101))
pop(key): - It removes the entry associated with the specified key and returns the
corresponding value. If the specified key is not available then we will get KeyError.
Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
print(d.pop(103))
print(d)
print(d.pop(130))
Special Sequences:
\d Matches any decimal digit; this is equivalent to the class [0-9].
\D Matches any non-digit character; this is equivalent to the class [^0-9].
\s Matches any whitespace character.
\S Matches any non-whitespace character.
\w Matches any alphanumeric character; this is equivalent to the class
[a-zA-Z0-9_].
\W Matches any non-alphanumeric character; this is equivalent to the class
[^a-zA-Z0-9_].
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
Ex:
import re
matcher=re.finditer('\d','a7b@k9z')
for m in matcher:
print(m.start()," ……….",m.group())
Quantifiers: These can be used to specify the number of occurrences to match.
Ex: Exactly one a → a
import re
matcher=re.finditer('a','abaabacab')
for m in matcher:
print(m.start()," ……….",m.group())
match() method: To check the given pattern at beginning of the target string or not. If it is
available then returns match object otherwise None.
Syntax
match(pattern, string)
Ex:
import re
s=input("Enter some pattern to check:")
m=re.match(s,'abcdefg')
if m!=None:
print("Match is available at begin of string")
print("Start index: {} and End index:{}".format(m.start(),m.end()))
else:
print("Match is not available at beginning of the string")
fullmatch(): -
Ex:
import re
s=input("Enter some pattern to check:")
m=re.fullmatch(s,'abcdefg')
if m!=None:
print("Full matched")
else:
print("Match is not available")
search() method:
Syntax:
re.search(pattern, string)
Ex:
import re
s=input("Enter some pattern to check:")
m=re.search(s,'abaabaaab')
if m!=None:
print("First occurrence with start index:{} and end index:{}".format(m.start(),m.end()))
else:
print("Not available")