PAP Module 3
PAP Module 3
DICTIONARIES
TUPLES
REGULAR EXPRESSIONS
>>> ls2=[3,4,1]
>>> print(ls2)
[3, 4, 1]
>>> print(ls[1])
hi
>>> print(ls[2])
[2, 3]
Mutable
as below
>>> ls=[34, 'hi', [2,3],-5]
>>> for item in ls:
print(item)
34
hi
[2,3]
-5
#output is
[1, 4, 9, 16]
t=['a','b','c','d','e']
Extracting full list without using any index, but only a slicing operator –
>>> print(t[:])
['a', 'b', 'c', 'd', 'e']
Extracting elements from 2nd position –
>>> print(t[1:])
['b', 'c', 'd', 'e']
>>> print(t[:3])
['a', 'b', 'c']
Selecting some middle elements –
>>> print(t[2:4])
['c', 'd']
Using negative indexing –
>>> print(t[:-2])
>>> print(t[::-1])
['e', 'd', 'c', 'b', 'a']
Application development using python, By: MANZOOR
KHAN, CS&E, GEC 15
append(): This method is used to add a new element at the end of a list.
>>> ls=[1,2,3]
>>> ls.append(“hi”)
>>> ls.append(10)
>>> print(ls)
>>> print(ls)
[-2, 3, 5, 10, 16]
When we want a list to be sorted in descending order, we need to set the argument
as shown
>>> ls.sort(reverse=True)
>>> print(ls)
>>> ls.reverse()
>>> print(ls)
[6, 1, 3, 4]
count(): This method is used to count number of occurrences of a particular value
within list.
>>> ls=[1,2,5,2,1,3,2,10]
>>> ls.count(2)
>>> ls=[1,2,3]
>>> ls.clear()
>>> print(ls)
[]
insert(): Used to insert a value before a specified index of the list.
>>> ls=[3,5,10]
>>> ls.insert(1,"hi")
>>> print(ls)
[3, 'hi', 5, 10]
The same function can be used with two more arguments start and end to specify a
range within which the search should take place.
>>> ls=[15, 4, 2, 10, 5, 3, 2, 6]
>>> ls.index(2)
2
>>> ls.index(2,3,7)
6
Note that, this function will remove only the first occurrence of the specified value,
but not all occurrences.
Unlike pop() function, the remove() function will not return the value that has been
deleted. Application development using python, By: MANZOOR
KHAN, CS&E, GEC 23
del: This is an operator to be used when more than one item to be deleted at a
time. Here also, we will not get the items deleted.
>>> ls=[3,6,-2,8,1]
>>> del ls[2] #item at index 2 is deleted
>>> print(ls)
[3, 6, 8, 1]
>>> ls=[3,6,-2,8,1]
>>> del ls[1:4] #deleting all elements from index 1 to 3
>>> print(ls)
[3, 1]
>>> print(t)
['a', 'c', 'e']
>>> print(avg)
11.857142857142858
Application development using python, By: MANZOOR
KHAN, CS&E, GEC 26
When we need to read the data from the user and to compute sum and average of
those numbers, we can write the code as below –
ls= list()
while (True):
x= input('Enter a number: ')
if x== 'done':
break
x= float(x)
ls.append(x)
>>> ls=list(s)
>>> print(ls)
>>> print(ls)
['Hello', 'how', 'are', 'you?']
Note that, when no argument is provided, the split() function takes the delimiter as
white space.
If we need a specific delimiter for splitting the lines, we can use as shown in
following example –
>>> dt="20/03/2018"
>>> ls=dt.split('/')
>>> print(ls)
Application development using python, By: MANZOOR
['20', '03', '2018'] KHAN, CS&E, GEC 29
There is a method join() which behaves opposite to split() function.
It takes a list of strings as argument, and joins all the strings into a single string
based on the delimiter provided.
>>> ls=["Hello", "how", "are", "you"]
………………
Apart from such lines, the log file also contains mail-contents, to-whom the mail
has been sent etc.
Application development using python, By: MANZOOR
KHAN, CS&E, GEC 31
Now, if we are interested in extracting only the days of incoming mails, then we can
go for parsing.
That is, we are interested in knowing on which of the days, the mails have been
received. The code would be –
fhand = open(“logFile.txt”)
words = line.split()
print(words[2])
b= “hi”
Now, the question is whether both a and b refer to the same string.
In the first situation, a and b are two different objects, but containing same value.
The modification in one object is nothing to do with the other.
Whereas, in the second case, both a and b are referring to the same object.
That is, a is an alias name for b and vice- versa. In other words, these two are
referring to same memory location.
>>> a= “hi”
>>> b= “hi”
When two variables are referring to same object, they are called as identical objects.
When two variables are referring to different objects, but contain a same value, they
are known as equivalent objects.
>>> ls1=[1,2,3]
def del_front(t):
del t[0]
OR
>>> eng2sp = dict()
>>> print(eng2sp)
{}
To add items to dictionary, we can use square brackets as –
>>> print(eng2sp)
{'one': 'uno'}
Application development using python, By: MANZOOR
KHAN, CS&E, GEC 40
To add items to dictionary, we can use square brackets as –
>>> d={}
>>> d["Mango"]="Fruit"
>>> d["Cucumber"]="Veg"
>>> print(d)
{'Mango': 'Fruit', 'Cucumber': 'Veg'}
To initialize a dictionary at the time of creation itself, one can use the code like –
>>> tel_dir={'Tom': 3491, 'Jerry':8135}
>>> print(tel_dir)
{'Tom': 3491, 'Jerry': 8135}
>>> tel_dir['Donald']=4793
>>> print(tel_dir)
{'Tom': 3491, 'Jerry': 8135, 'Donald': 4793}
NOTE that the order of elements in dictionary is unpredictable. That is, in the above
example, don‟t assume that 'Tom': 3491 is first item, 'Jerry': 8135 is second item etc.
8135
Here, the key 'Jerry' maps with the value 8135, hence it doesn‟t matter where
exactly it is inside the dictionary.
If a particular key is not there in the dictionary and if we try to access such key,
then the KeyError is generated.
>>> print(tel_dir['Mickey'])
KeyError: 'Mickey'
The in operator can be used to check whether any key (not value) appears in the
dictionary object.
>>> 'Mickey' in tel_dir #output is False
>>> 'Jerry' in tel_dir #output is True
>>> 3491 in tel_dir #output is False
1. Create 26 variables to represent each alphabet. Traverse the given string and increment
the corresponding counter when an alphabet is found.
2. Create a list with 26 elements (all are zero in the beginning) representing alphabets.
Traverse the given string and increment corresponding indexed position in the list when
an alphabet is found.
3. Create a dictionary with characters as keys and counters as values. When we find a
character for the first time, we add the item to dictionary. Next time onwards, we
increment the value of existing item.
print(d)
In the above program, for every character ch in a given string, we will try to retrieve
a value. When the ch is found in d, its value is retrieved, 1 is added to it, and
restored.
If ch is not found, 0 is taken as default and then 1 is added to it.
Output would be –
Tom 3491
Jerry 8135
Mickey 1253
Output:
Tom 3412
Jerry 6781
Mickey 1294
The usage of comma-separated list k,v here is internally a tuple (another data
structure in Python, which will be discussed later).
d=dict()
for line in fhand:
for word in line.split():
d[word]=d.get(word,0)+1
print(d)
An empty tuple can be created either using a pair of parenthesis or using a function
tuple() as below
>>> t1=()
>>> type(t1)
<class 'tuple'>
>>> t2=tuple()
>>> type(t2)
<class 'tuple'>
>>> t=tuple('Hello')
>>> print(t)
>>> t=tuple([3,[12,5],'Hi'])
>>> print(t)
>>> t = list(d.items())
>>> print(t)
[('b', 1), ('a', 10), ('c', 22)]
import re
if re.search('how', line):
print(line)
By referring to file myfile.txt that has been discussed in previous Chapters, the
output would be
import re
hand = open('myfile.txt')
if re.search('^how', line):
print(line)
import re
fhand = open('myfile.txt')
for line in fhand:
line = line.rstrip()
if re.search('^h.+u', line):
print(line)
import re
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
pattern = “^[Ff]rom.*edu$‟
if re.search(pattern, line):
print(line)
Application development using python, By: MANZOOR
KHAN, CS&E, GEC 78
Pattern to extract lines ending with any digit:
pattern = “[0-9]$”
Using Not :
pattern = “^[^a-z0-9]+”
pattern = '^[A-Z].*[0-9]$'
Output: ['$10.00']
Here, we want to extract only the price $10.00. As, $ symbol is a metacharacter, we
need to use \ before it.
So that, now $ is treated as a part of matching string, but not as metacharacter.