Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

Python Module 3

The document provides information on lists, tuples, and sets in Python. It discusses how lists allow duplicate and heterogeneous elements and preserve insertion order. Tuples are like immutable lists. Sets do not allow duplicates and do not preserve insertion order. The document describes how to define, access elements of, traverse, modify and perform operations on lists, tuples and sets in Python. It also compares lists and tuples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Python Module 3

The document provides information on lists, tuples, and sets in Python. It discusses how lists allow duplicate and heterogeneous elements and preserve insertion order. Tuples are like immutable lists. Sets do not allow duplicates and do not preserve insertion order. The document describes how to define, access elements of, traverse, modify and perform operations on lists, tuples and sets in Python. It also compares lists and tuples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

List:

• 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

• By using slice operator:


Syntax:
list2=list[start:end:step]
start → It indicates the index where slice has to start. Default is 0.
end → It indicates the index where slice has to end. Default is length of
the list.
step → Increment value. Default value is 1.

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]

Traversing elements of List:


Using while loop:
Ex:
a=[34,87,21,56]
i=0
while i<len(l):
print(a[i])
i=i+1

Using for loop:


Ex:
a=[34,87,21,56]
for x in a:
print(x)

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))

count(element): - Count the specified element in the list.


Ex:
a=[23,54,65,23,65,34,23,77]
print(a.count(23))
print(a.count(54))

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))

append(element): - This function is used to add the element to the list.


Ex:
a=[10,22,33,44]
print(a)
a.append(55)
print(a)

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)

remove(): - This function is used to remove an element from the list.


If duplicates are found then first occurrence will be removed.
If element is not found then it displays ValueError.
Ex:
a=[34,53,11,87,53]
print(a)
a.remove(53)
print(a)
a.remove(50) #ValueError
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)

reverse(): - This function is used to reverse the elements of the list.


Ex:
l=[10,4,30,6]
print(l)
l.reverse()
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)

Aliasing and Cloning of list objects:


The process of giving another reference variable to the existing list is called aliasing.
Ex:
x=[10,20,30,40]
y=x
print(id(x))
print(id(y))
print(x)
print(y)
x[2]=88
print(x)
print(y)

→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: Using slice operator


x=[10,20,30,40]
y=x[:]
print(id(x))
print(id(y))
print(x)
print(y)
x[2]=88
print(x)
print(y)

Ex: Using copy() function


x=[10,20,30,40]
y=x.copy()
y[1]=777
print(x)
print(y)

Using mathematical operators for list objects:


We can use + and * operators for list objects.
Concatenation operator (+):
We can use + to concatenate 2 lists into single list.

Ex:
l1=[1,2,3]
l2=[4,5,6]
l3 = l1+l2
print(l3)

Repetition operator (*):


We can use repetiotion operator * to repeat elements of list specified number of times.
Ex:
x=[1,2,3]*3
print(x)

Comparision list objects:


We can use comparision operators for list objects.
Ex:
x=["Dog","Cat","Rat"]
y=["Dog","Cat","Rat"]
z=["DOG","CAT","RAT"]
print(x==y) #True
print(x==z) #False
print(x!=z) #True

Membership operators: in & not in


We can check whether element is a member of the list or not by using membership
operators.
Ex:
n=[10,20,30,40]
print(10 in n)
print(10 not in n)
print(50 in n)
print(50 not in n)

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.

Nested list as matrix:


In Python we can represent matrix by using nested lists.
Ex:
n=[[10,20,30],[40,50,60],[70,80,90]]
print("Elements in Matrix style:")
for i in range(len(n)):
for j in range(len(n[i])):
print(n[i][j],end=" ")
print()

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))

Accessing elements of tuple:


We can access either by index or by slice operator.

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])

Using while loop:


t=(10,20,30,40,45,33,22)
i=0
while i<len(t):
print(t[i])
i=i+1

Using for loop:


t=(10,20,30,40,45,33,22)
for x in t:
print(x)

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

Mathematical operators for tuple:


We can apply + and * operators for tuple.
Concatenation operator(+):
Ex:
t1=(10,20,30)
t2=("abc","xyz")
t3=t1+t2
print(t3)
Multiplication operator or repetition operator (*):
Ex:
t1=(10,20,30)
t2=t1*3
print(t2)
Tuple functions:
len(): - To return number of elements present in the tuple.
Ex:
t=(10,20,30,40)
print(len(t)) #4

count(element): - To return number of occurrences of given element in the tuple.


Ex:
t=(10,20,10,10,20)
print(t.count(10)) #3

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.

sorted(): - To sort the elements based on natural sorting order.


Ex:
t1=(10,50,23,40)
t2=sorted(t1)
print(t1)
print(t2)

min(): - It returns smallest value in the tuple.


max(): - It returns highest value in the tuple.
Ex:
t1=(10,50,23,40,22,55,43)
print("Smallest value=",min(t1))
print("Highest value=",max(t1))

Tuple packing and un-packing


Packing:
Group the different individual values into tuple.
Ex:
a,b,c,d=10,20,30,40
t=a,b,c,d
print(t)

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.

Difference between List and Tuple:


→List and Tuple are exactly same except small difference: List objects are mutable where
as Tuple objects are immutable.
→In both cases insertion order is preserved, duplicate objects are allowed, heterogenous
objects are allowed, index and slicing are supported.
Set: -
→If you want to represent a group of unique values as a single entity then we should go for
set.
→We can represent set elements within curly braces with comma separation.
→Duplicates are not allowed.
→Insertion order is not preserved. But we can sort the elements.
→Indexing and slicing are not allowed for the set.
→Heterogeneous elements are allowed.
→Set objects are mutable that is once we create set object we can perform any changes in
that object based on our requirement.
→We can apply mathematical operations like Union, Intersection, Difference etc. on set
objects.
Ex:
s={10,20,30,40}
print(type(s))
print(s)

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)

copy(): - Returns copy of the set. It is cloned object.


Ex:
s1={10,20,30}
s2=s1.copy()
print(s1)
print(s2)

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())

remove(element): - To remove the specified element. If element is not found then it


displays KeyError.
Ex:
s={10,20,30,40}
s.remove(40)
print(s)
s.remove(140)

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)

clear(): - To remove all elements from the set.


Ex:
s={10,20,30,40}
print(s)
s.clear()
print(s)

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.intersection(set2): - Returns an intersection of two sets. Using the ‘&’ operator


between two sets is the same as writing set1.intersection(set2).
set1.intersection(set2) or set1&set2
Ex:
s1={10,20,30,40}
s2={30,40,50,60}
print(s1.intersection(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)

set1.symmetric_difference(set2): - The elements present inside set1 but not in set2,


present inside set2 but not in set1. Using the ‘^’ operator between two sets is the same as
writing set1.symmetric_difference(set2).
set1.symmetric_difference(set2) or set1^set2
Ex:
s1={10,20,30,40}
s2={30,40,50,60}
print(s1.symmetric_difference(s2))
print(s1^s2)
Dictionary:
→If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.
Ex:
admno name
username password
mobileno network
→Dictionaries can be created using pair of curly braces ( {} ). Each item in the dictionary
consist of key, followed by a colon, which is followed by value. And each item is separated
using comma (,)
→An item has a key and the corresponding value expressed as a pair, key: value.
→Duplicate keys are not allowed but values can be duplicated.
→Heterogeneous objects are allowed for both key and values.
→Insertion order is preserved.
→It is mutable.
→Indexing and slicing are not applicable.

Creating dictionary:
Empty dict:
d={}
#d=dict()
d[100]='satish'
d[103]='lokesh'
d[104]='rajesh'
print(type(d))
print(d)

Accessing elements from dictionary:


We can access data by using keys.
Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
print(d[103])
print(d[303])
→If key is not found then it returns KeyError.
Update dictionary:
d[key]=value
→If key is available then only value will be replaced.
→If key is not available then new entry will be added.
Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
d[100]='lohit'
d[105]='ravi'
print(d)

How to delete elements from dictionary:


del d[key]
→If key is available then total entry will be deleted.
→If key is not available then we will get KeyError.
Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
print(d)
del d[100]
print(d)
del d[105]
print(d)

To provide multiple values for key:


Ex:
l=[10,20,30]
d={100:l}
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))

keys(): - It returns all keys associated with dictionary.


Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
print(d.keys())
for k in d.keys():
print(k)

values(): - It returns all values associated with dictionary.


Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
print(d.values())
for k in d.values():
print(k)

items(): It returns list of tuples representing key-value pairs.


[(k,v),(k,v)]
Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
print(d.items())
copy(): To create exactly duplicate dictionary.
Ex:
d={100:'satish', 103:'lokesh', 104:'rajesh'}
print(d)
d1=d.copy()
print(d1)

update(): - It is used to add items of second dictionary to first dictionary.


Ex:
d1={100:'satish', 103:'lokesh', 104:'rajesh'}
d2={'a':'apple','b':'banana'}
d1.update(d2)
print(d1)
Regular Expressions
A regular expression is a sequence of letters and some special characters (also called meta
characters). These special characters have symbolic meaning. The sequence formed by
using meta characters and letters can be used to represent a group of patterns.
Main important application areas of regular expressions:
1. Validations.
2. To develop pattern matching applications.
3. Translators like compilers, interpreters, assemblers …
4. To develop digital circuits.
5. Communication protocols TCP/IP etc.

→We use re module to perform regular expressions.

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())

Ex: Atleast one a → a+


import re
matcher=re.finditer('a+','abaabacab')
for m in matcher:
print(m.start()," ……….",m.group())

Ex: Any number of a’s including 0 number also → a*


import re
matcher=re.finditer('a*','abaabacab')
for m in matcher:
print(m.start()," ……….",m.group())

Ex: At least one a (either one a or zero number of a) → a?


import re
matcher=re.finditer('a?','abaabacab')
for m in matcher:
print(m.start()," ……….",m.group())

Ex: Exactly n number of a’s → a{n}


import re
matcher=re.finditer('a{2}','abaabacab')
for m in matcher:
print(m.start()," ……….",m.group())

Ex: Minimum n number of a’s and maximum n number of a’s → a{m,n}


import re
matcher=re.finditer('a{2,4}','abaabaaacab')
for m in matcher:
print(m.start()," ……….",m.group())
Important functions in re module: -
match(), fullmatch(), search(), findall(), finditer(), sub(), split(), compile()

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")

findall(): - All the occurrences of returns list.


Ex:
import re
l=re.findall('[0-9]','a7b9k6s')
print(l)

finditer(): -It returns iterator of matched objects.


Ex:
import re
matcher=re.finditer('\d','a7bk9z7')
for m in matcher:
print(m.start(),m.end(),m.group())

sub(): - Substitution or replacement.


Syntax:
sub(regex,replacement,targetstring)
Ex:
import re
s=re.sub('\d','#','a7b9k5t9k')
print(s)

subn(): - Substitution or replacement.


Syntax:
re.subn(regex,replacement,targetstring)
It returns tuple (resultstring, noof replacements)
Ex:
import re
t=re.subn('\d','#','a7b9k5t9k')
print("The result string:",t[0])
print("The no of replacements:",t[1])

You might also like