Newunit 4
Newunit 4
COMPOUND DATA:
LISTS, TUPLES, DICTIONARIES
4.1 LISTS
A list is a sequence of any type of values and can be created as a set of comma-separated
values within square brackets. The values in a list are called elements or items. A list within another
list is called nested list.
Sample Output:
[‘Ram’, ‘Chennai’, 2017]
[10, 20, 30, 40, 50] [ ]
[‘Priya’, 2017, 99.8, [‘Mumbai’, ‘India’]]
For eg, in a list stulist = [‘Ram’, ‘Chennai’, 2017], stulist[1] returns Chennai as its output.
The following code is another example for concatenation, where a list contains elements of
different data types:
Code Output
stulist = [‘Ram’, ‘Chennai’, 2017] [‘Ram’, ‘Chennai’, 2017]
newlist = stulist+[‘CSE’] [‘Ram’, ‘Chennai’, 2017, ‘CSE’]
print stulist
print newlist
If the first index is omitted, the slice starts at the beginning of the string. If the second index
is omitted, the slice goes to the end of the string. If the first index is greater than or equals to the
second, the slice is an empty string. If both indices are omitted, the slice is a given string itself.
Compound Data: Lists, Tuples, Dictionaries 4.3
1. append
Adds element to the end of specified list and does not return any value.
Syntax: listname.append(element)
Sample output:
After appending
[‘Ram’, ‘Chennai’, 2017, ‘CSE’]
2. count
Returns the number of occurrences of an element in a specified list.
Syntax: listname.count(element)
3. extend
Appends the contents of secondlist to the firstlist and does not return any value.
Syntax: firstlist.extend(secondlist)
Sample output:
Before Extend : [‘Ram’, ‘Chennai’, 2017]
After Extend : [‘Ram’, ‘Chennai’, 2017, ‘CSE’]
4. index
Returns the index of an element, if an element is found in the specified list. Else, an exception
is raised.
Syntax: listname.index(element)
Sample output:
Index of Ram : 0
Index of Chennai : 1
Index of 2017 : 2
Compound Data: Lists, Tuples, Dictionaries 4.5
6. insert
Inserts the given element at the given index in a specified list and does not return any value
Syntax: listname.insert(index, element)
Sample output:
Before insert : [‘Ram’, ‘Chennai’, 2017]
After insert : [‘Ram’, ‘CSE’, ‘Chennai’, 2017]
7. pop
Removes and returns the element from the end of specified list
Syntax: listname.pop()
Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
Popping the last item : 92.7
After popping the last item, the list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’]
8. pop(index)
Removes and returns the element at given index.
Syntax: listname.pop(index)
9. remove
Removes an element from the list and does not return any value.
Syntax: listname.remove(element)
Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7, 2017]
After removing CSE from the list : [‘Ram’, ‘Chennai’, 2017, 92.7, 2017]
After removing 2017 from the list : [‘Ram’, ‘Chennai’, 92.7, 2017]
10. reverse
Reverses the entire list
Syntax: listname.reverse()
Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
After reversing, the list is : [92.7, ‘CSE’, 2017, ‘Chennai’, ‘Ram’]
Compound Data: Lists, Tuples, Dictionaries 4.7
11. sort
Sorts the list in ascending order.
Syntax: listname.sort()
Sample output:
Before sorting : [6, 28, 11, 4, 20, 26, 13, 12]
After sorting is : [4, 6, 11, 12, 13, 20, 26, 28]
stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
print ‘Initial list is : ‘, stulist
stulist.sort()
print ‘After sorting, the list is : ‘, stulist
Sample output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
After sorting, the list is : [92.7, 2017, ‘CSE’, ‘Chennai’, ‘Ram’]
for i in range(len(numlist)):
print i
Output:
0
1
2
3
4
Here, len is a function that returns the number of elements in the list and range is a function
that returns a list of indices from 0 to n − 1, where n is the length of the list. The following code
gives an idea to traverse the list and to update the elements of a list with the help of range and len
functions in for loop:
numlist = [1, 2, 3, 4, 5]
for i in range(len(numlist)):
numlist[i]=numlist[i]+10
for i in numlist:
print i
Output:
11
12
13
14
15
A for loop over an empty list never executes the body and is shown in the following code:
numlist = []
for i in numlist:
print ‘never executes’
4.1.6 Mutability
The list is a mutable data structure. This means that its elements can be replaced, inserted
and removed. A slice operator on the left side of an assignment operation can update single or
multiple elements of a list. New elements can be added to the list using append() method.
The following code replaces ‘Ram’ which is at index 0 in the stulist by ‘Priya’. The values
are shown in the output for both instances.
stulist = [‘Ram’, ‘Chennai’, 2017]
print ‘Before mutation ‘, stulist
Compound Data: Lists, Tuples, Dictionaries 4.9
stulist[0] = ‘Priya’
print ‘After mutation ‘, stulist
Output:
Before mutation [‘Ram’, ‘Chennai’, 2017]
After mutation [‘Priya’, ‘Chennai’, 2017]
4.1.7 Aliasing
When we create two lists, we get two objects as shown in the following code and the
corresponding state diagram (Figure 4.1):
list1=[1,2]
list2=[1,2]
print list1 is list2 # prints False, as list1 and list2 are not the same object
List 1 [1,2]
List 2 [1,2]
In the following code, there are two references to the same object. An object with more than
one reference has more than one name, so we say that the object is aliased.
list1=[1,2]
list2=list1
print list1 is list2 # prints True, as list1 and list2 are the same object
The state diagram for the above code is as shown in Figure 4.2:
List 1
[1,2]
List 2
If the aliased object is mutable, modifications done in one object affect the other object
also. In the following code, list1 and list2 are aliased objects. Changes made in list1 affect list2 and
similarly, changes done in list2 affect list1.
4.10 Problem Solving and Python Programming
Sample Code
list1=[1,2]
list2=list1
print ‘List1 is :’, list1
print ‘List2 is :’, list2
list1[0]=10
print ‘List1 is :’, list1
print ‘List2 is :’, list2
list2[1]=20
print ‘List1 is :’, list1
print ‘List2 is :’, list2
Sample Output:
List1 is : [1, 2]
List2 is : [1, 2]
List1 is : [10, 2]
List2 is : [10, 2]
List1 is : [10, 20]
List2 is : [10, 20]
Though aliasing can be helpful, it may lead to errors. So, avoid aliasing in mutable objects.
To prevent aliasing in lists, a new empty list can be created and the contents of the existing list can
be copied to it, as given in the following code:
Output:
List1 is : [1, 2]
List2 is : [1, 2]
After modification
List1 is : [10, 2]
List2 is : [1, 2]
In lists, cloning operation can be used to create a copy of an existing list so that changes
made in one copy of list will not affect another. The copy contains the same elements as the original.
Sample Code:
oldlist = [10, 20, 30, 40, 50]
newlist = list(oldlist)
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
oldlist[0]=5
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
Sample Output:
Old list is : [10, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Old list is : [5, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
copy.copy() is little slower than list() since it has to determine data type of old
list first.
4.12 Problem Solving and Python Programming
Sample Code:
import copy
oldlist = [10, 20, 30, 40, 50]
newlist = copy.copy(oldlist) # Returns a shallow copy of oldlist
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
oldlist[0]=5
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
Sample Output:
Old list is : [10, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Old list is : [5, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Sample Code:
import copy
oldlist = [10, 20, 30, 40, 50]
newlist = copy.deepcopy(oldlist) # Returns a deep copy of oldlist
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
oldlist[0]=5
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
Sample Output:
Old list is : [10, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Old list is : [5, 20, 30, 40, 50]
New list is : [10, 20, 30, 40, 50]
Compound Data: Lists, Tuples, Dictionaries 4.13
copy() (also known as shallow copy) and deepcopy() differs in the usage of compound objects
that are objects containing other objects, like lists). copy() creates a new compound object first and
then inserts references to the objects of the original. deepcopy() constructs a new compound object
and then, recursively, inserts copies to the objects of the original. The following code illustrates the
use of deepcopy() for a compound (nested) list.
Sample Code:
import copy
oldlist = [1, 2, [‘a’,’b’]]
newlist = copy.deepcopy(oldlist)
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
newlist[0] = ‘c’
newlist[2][1] = ‘d’
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
Sample Output:
Old list is : [1, 2, [‘a’, ‘b’]]
New list is : [1, 2, [‘a’, ‘b’]]
Old list is : [1, 2, [‘a’, ‘b’]]
New list is : [‘c’, 2, [‘a’, ‘d’]]
The following program employs a function my_display() that creates and returns a new list.
Within my_display(), numlist is referenced as n.
Sample Code:
def my_display(n): # function definition
return n[:]
numlist = [10, 20, 30, 40, 50]
print ‘numlist is : ‘, numlist
newlist=my_display(numlist) # function call
print ‘newlist is : ‘, newlist
Sample Output:
numlist is : [10, 20, 30, 40, 50]
newlist is : [10, 20, 30, 40, 50]
The following program includes a function my_display() that creates and displays the
elements of a list.
Sample Code:
def my_display(n): # function definition
nlist= n[:]
print ‘Within a function : ‘, nlist
numlist = [10, 20, 30, 40, 50]
print ‘numlist is : ‘, numlist
my_display(numlist) # function call
Sample Output:
numlist is : [10, 20, 30, 40, 50]
Within a function : [10, 20, 30, 40, 50]
del stulist[1]
print ‘Now the list is : ‘, stulist
Output:
Initial list is : [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
Now the list is : [‘Ram’, 2017, ‘CSE’, 92.7]
pop() and remove() methods can also be used to delete list elements.
Code Output
list1 = [10, ‘xyz’]
list2 = [20, ‘abc’]
list3 = [10, ‘xyz’]
print ‘Comparing list1 and list2 ‘, cmp(list1, list2) Comparing list1 and list2 -1
print ‘Comparing list2 and list3 ‘, cmp(list2, list3) Comparing list2 and list3 1
print ‘Comparing list1 and list3 ‘,cmp(list1, list3) Comparing list1 and list3 0
1. len
Returns the total number of elements in a list.
Syntax: len(listname)
Code Output
stulist = [‘Ram’, ‘Chennai’, 2017, ‘CSE’, 92.7]
print ‘Length is : ‘, len(stulist) Length is : 5
2. max
Returns the largest item from the list
Syntax: max(listname)
3. min
Returns the smallest item from the list
Syntax: min(listname)
4.16 Problem Solving and Python Programming
Code Output
numlist = [6, 28, 11, 4, 20, 26, 13, 12]
print ‘Maximum is : ‘, max(numlist) Maximum is : 28
print ‘Minimum is : ‘, min(numlist) Minimum is : 4
stulist = [‘Anu’, ‘Chennai’, 2017, ‘CSE’, 92.7]
print ‘Maximum is : ‘, max(stulist) Maximum is : Chennai
print ‘Minimum is : ‘, min(stulist) Minimum is : 92.7
4. list
Converts a tuple into a list and returns a list.
Syntax: listname=list(tuplename)
Code Output
stu_tuple = (‘Anu’, ‘Chennai’, 2017, ‘CSE’, 92.7) Tuple elements : (‘Anu’, ‘Chennai’,
print ‘Tuple elements : ‘, stu_tuple 2017, ‘CSE’, 92.7)
stulist = list(stu_tuple) List elements : [‘Anu’, ‘Chennai’,
print ‘List elements : ‘, stulist 2017, ‘CSE’, 92.7]
Syntax:
[expression for item in list if conditional]
This is equivalent to:
for item in list:
if conditional:
expression
new_list = [expression(i) for i in old_list if filter(i)]
new_list is the resultant list. expression(i) is based on the variable used for each element in
the old list. If needed filter can be applied using if statement.
Compound Data: Lists, Tuples, Dictionaries 4.17
Example:
from types import *
a_list = [1, ‘4’, 9, ‘a’, 0, 4]
squared_ints = [ e**2 for e in a_list if type(e) == IntType ]
print squared_ints
Sample output:
[ 1, 81, 0, 16 ]
Output Input
Expression Sequence
•• The iterator part iterates through each member e of the input sequence a_list.
•• The predicate checks if the member is an integer.
•• If the member is an integer then it is passed to the output expression, squared, to become
a member of the output list.
Example:
x=[I for I in range(10)]
print x
Sample Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares=[x**2 for x in range(10)]
print squares
Sample Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Sample Output:
[‘t’, ‘i’, ‘a’, ‘e’]
4.18 Problem Solving and Python Programming
Sample Output:
[11, 12, 13, 21, 22, 23, 31, 32, 33]
This example, adds the values in list x to each value in list y.
4.2 TUPLES
A tuple is a collection of values of different types. Unlike lists, tuple values are indexed by
integers. The important difference is that tuples are immutable.
•• Tuples generally used for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
•• Tuples are immutable, so iterating through tuple is faster than with list. There is a slight
performance enhancement through list.
•• Tuple elements can be used as key for a dictionary. With list, this is not possible.
•• If you have data that doesn’t change, implementing it as tuple will guarantee that it
remains write-protected.
As we have seen before, a tuple is a comma-separated values.
Syntactically, a tuple can be represented like this:
>>> t = ‘a’, ‘b’, ‘c’, ‘d’, ‘e’
Even if it is not necessary to parentheses to enclose tuples, it is so.
t1 = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
t2=(1,2,3,4,5)
The empty tuple can be created by simply using the parentheses.
t3=()
The tuple with one element can be created as follows. It takes one comma after the element.
t4=(‘s’,)
print type(t4)
Output:
<type ‘tuple’>
Compound Data: Lists, Tuples, Dictionaries 4.19
t5 = ‘a’,
print type(t5)
Output:
<type ‘tuple’>
A value of tuple in parentheses is not a tuple. The following program code explain this.
t2 = (‘a’)
print type(t2[1])
Output:
<type ‘str’>
The built –in function tuple can be used to create tuple. To create an empty tuple no arguments
is passed in the built-in function.
t = tuple() #tuple is the built-in function
print t
Output:
()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of
the sequence:
t = tuple(‘hello’)
print t
Output:
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
t = tuple(’12345’)
print t
Output:
(‘1’, ‘2’, ‘3’, ‘4’, ‘5’)
tup2 = (“hai”,)
print type(tup2)
# parentheses is optional
tup3 = “hai”,
print type(tup3)
Output:
<class ‘str’>
<class ‘tuple’>
<class ‘tuple’>
Output:
tup1[0]: C
tup1[1]: C++
tup2[1:5]: [2, 3, 4, 5, 6, 7]
a
Output:
p
n
t
n
p
o
6
1
Output:
(‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
4.22 Problem Solving and Python Programming
Here, the first element ‘a’ is replaced with ‘A’. A new tuple is created with the value ‘A’ is
combined with tuple t3 having index from 1 to the last element. The tuple value t3[0]=’a’ is replaced
by ‘A’.
Output:
(‘C’, ‘C++’, ‘python’, 1997, 2000)
After deleting :
print t1
Output:
1
2
In general to swap the values of two variables, a temporary variable is used. For example
to swap x and y:
temp = x
x=y
y = temp
This solution is clumsy; the tuple assignment is more elegant.
a, b = b, a
In the expression, the left side is a tuple of variables; the right side is a tuple of expressions.
Each value is assigned to its respective variable. All the expressions on the right side are evaluated
before any of the assignments.
4.24 Problem Solving and Python Programming
The number of variables on the left side and the number of values on the right must be the
same:
a, b = 1, 2
In this a is assigned with 1 and b is assigned with 2.
For the assignment,
a, b= 1,2,3
This statement creates error, as
ValueError: too many values to unpack
The right side of the assignment statement can be any kind of sequence (string, list or tuple).
For example, to split an email address into a user name and a domain, the split function can be used
as follows.
mail_id = ‘students@python.org’
uname, domain = mail_id.split(‘@’)
print uname
print domain
Output:
students
python.org
In this, the split function is used to separate the value into two parts. The return value from
the split function is a list with two elements; the first element is assigned to uname, the second is
assigned to domain.
print t4
# tuple can be created without parentheses (called tuple packing)
t5 = 3, 4.6, “ABC”
print t5
# tuple unpacking is also possible
#tuple assignment
x, y, z = t5
print x
print y
print z
Output:
()
(1, 2, 3)
(1, ‘Hello’, 2.4)
(‘World’, [8, 4, 6], (1, 2, 3))
(3, 4.6, ‘ABC’)
3
4.6
ABC
Output:
True
False
False
True
Progrmming-languages C
Progrmming-languages C++
Output:
(2, 1)
Here, the built-in function divmod is used which takes two arguments and returns a tuple of
two values, the quotient and remainder. The result can be stored as a tuple as in previous program
code. Or tuple assignment can be used to store the elements separately as in the following code.
Compound Data: Lists, Tuples, Dictionaries 4.27
Output:
2
1
One more example to explain tuples as return values. The built-in functions min and max
are used to find the smallest and largest elements of a sequence. The function min_max computes
both and returns a tuple of two values.
Example:
def printall (*args): # the function takes several args
print args
4.28 Problem Solving and Python Programming
The argument name may be anything, but args is conventional. Here is the example to show
how the function printall works:
printall(1, 2.0, ‘3’)
(1, 2.0, ‘3’)
The complement of gather is scatter. To pass a sequence of values to a function as multiple
arguments, the * operator can be used. For example, consider the divmod function which takes
exactly two arguments; doesn’t work with a tuple of variable length arguments:
t = (7, 3)
divmod(t)
Output:
TypeError: divmod expected 2 arguments, got 1
Output:
3
The sum function does not take variable length arguments. It gives error.
sum(1,2,3)
Output:
TypeError: sum expected at most 2 arguments, got 3
True
Compound Data: Lists, Tuples, Dictionaries 4.29
The sort function also works in the same way. It sorts primarily by first element. But if there
is a tie, it sorts by second element, and so on. This feature lends itself to a pattern called DSU. DSU
stands for Decorate, Sort, Undecorate.
DSU:
Decorate a sequence by building a list of tuples with one or more sort keys preceding the
elements from the sequence,
Sort the list of tuples, and Undecorate by extracting the sorted elements of the sequence.
Output:
-1
1
-1
1
0
0
-1
1
4.3 DICTIONARIES
Dictionary is an unordered collection of items. It is similar to a list, but in list elements can
be accessed using index which must be an integer. In Dictionary we access values by looking up a
key instead of an index. A key can be any string or number. For example, dictionaries can be used
for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail
address with a username).
Each item in dictionary has a key: value pair and the list of items are enclosed inside curly
braces {} separated by comma. The values can be of any data type and can repeat; keys must be of
immutable types (string, number or tuple with immutable elements) and must be unique.
Dictionaries in Python are implemented using hash table. It is an array whose indexes are
obtained using a hash function on the keys. A hash function takes a key value and returns hash
value, an integer. This hash value is used in the dictionary to store and lookup key-value pairs. So
keys in dictionary must be hashable.
# empty dictionary
my_dict = {}
print my_dict
Sample Output:
{}
The following dictionary uses integer as keys and string as values.
# dictionary with integer keys
my_dict = {1: ‘apple’, 2: ‘ball’}
print my_dict
print my_dict[2]
Compound Data: Lists, Tuples, Dictionaries 4.31
Sample Output:
{1: ‘apple’, 2: ‘ball’}
ball
The following dictionary uses mixed keys. For item 1, both key and its corresponding value
are string. In item 2, the key is an integer and the value is a list.
Sample Output:
{1: [2, 4, 3], ‘name’: ‘John’}
John
[2, 4, 3]
In the output, the order of the key-value pairs is not the same. In general, the order of items
in dictionary is unpredictable. In the following example, using list, a mutable data type as key
results in error message.
dic = { [1,2,3]:”abc”}
Traceback (most recent call last):
File “main.py”, line 1, in <module>
dic = { [1,2,3]:”abc”}
TypeError: unhashable type: ‘list’
Tuple, an immutable data type can be used as key, which is shown in following example.
my_dic = { (1,2,3):”abc”, 3.14:”abc”}
print my_dic
Sample Output:
{3.14: ‘abc’, (1, 2, 3): ‘abc’}
An exception will be raised when we try to access a key that not exist in dictionary. In the
following example, accessing my_dict[2] results in an error, as the key 2 not exist in dictionary.
my_dict = {‘name’: ‘John’, 1: [2, 4, 3]}
print my_dict[2]
4.32 Problem Solving and Python Programming
Sample Output:
Traceback (most recent call last):
File “main.py”, line 2, in <module>
print my_dict[2]
KeyError: 2
Dictionaries can also be created using the dict() function.
# using dict()
my_dict = dict({1:’apple’, 2:’ball’})
print my_dict
Sample Output:
{1: ‘apple’, 2: ‘ball’}
Function/Method Description
len(dict) Returns the length of dictionary which is equal to
number of pairs in the dictionary.
cmp(dict1,dict2) Compare items of two dictionaries
sorted(dict) Returns sorted list of keys in dictionary
dict.clear() Remove all items from dictionary
dict.copy() Returns a shallow copy of dictionary
dict.fromkeys(seq[, v]) Return a new dictionary with keys from seq and value
equal to v
dict.get(key) Returns the value of key. If key does not exists, it returns
None
dict.pop(key) Remove the item with key and returns its value.
KeyError occurs when key is not found
dict.popitem() Remove and return an arbitary item (key, value). Raises
KeyError if the dictionary is empty.
dict.items() Returns a list of dict’s (key, value) tuple pairs
dict.keys() Returns list of dictionary dict’s keys
dict1.update(dict2) Update the dictionary dict1 with the key/value pairs
from dict2, overwriting existing keys.
So we can add new items or change the value of existing items. If the key is present, its value gets
updated. Else a new key:value pair is added to dictionary.
my_dict={‘name’:’Ram’,’age’:21}
print my_dict # display all items
print my_dict.get(‘name’) # Retrieves the value of name key
my_dict[‘age’]=23 # update value
print my_dict
my_dict[‘dept’]=’CSE’ # add item
print my_dict
Sample Output:
{‘age’: 21, ‘name’: ‘Ram’}
{‘age’: 23, ‘name’: ‘Ram’}
{‘dept’: ‘CSE’, ‘age’: 23, ‘name’: ‘Ram’}
Sample Output:
9
{1: 1, 2: 4, 4: 16, 5: 25}
(1, 1)
{2: 4, 4: 16, 5: 25}
{2: 4, 4: 16}
{}
4.34 Problem Solving and Python Programming
We can also use the del keyword to remove individual items or the entire dictionary itself.
If we try to access the deleted dictionary, it will raise an Error.
del squares # delete the dictionary itself
print squares #throws error
Traceback (most recent call last):
File “main.
py”, line 11, in <module>
print squares NameError: name ‘squares’ is not defined
Sample Output:
{‘Maths’: 0, ‘Science’: 0, ‘English’: 0}
(‘Maths’, 0)
(‘Science’, 0)
(‘English’, 0)
[‘English’, ‘Maths’, ‘Science’]
value=dict[key]
Whereas, reverse lookup is the process of finding the key for a given value. There is no
direct method to handle reverse lookup. The following function takes a value and returns the first
key that map to that value.
def get_Value(dic,value):
for name in dic:
if dic[name] == value:
return name
raise ValueError
squares={1:1,2:4,3:9,4:16,5:25}
print get_Value(squares,4) # successful reverse lookup
Sample Output:
2
In this example, raise keyword is used to raise/activate an exception. ValueError indicates
that there is something wrong with value of parameter. On unsuccessful reverse lookup, when the
value is not in the dictionary, the exception ValueError is raised. Unsuccessful reverse lookup result
in following error.
print get_Value(squares,6) # unsuccessful reverse lookup
Traceback (most recent call last):
File “main.py”, line 7, in <module>
print get_Value(squares,6)
File “main.py”, line 5, in get_Value
raise ValueError
ValueError
return newdict
d = {‘child1’: ‘parent1’,
‘child2’: ‘parent1’,
‘child3’: ‘parent2’,
‘child4’: ‘parent2’,
}
print invert_dict_nonunique(d)
Sample Output:
{‘parent2’: [‘child3’, ‘child4’], ‘parent1’: [‘child1’, ‘child2’]}
In this example the loop iterates through dictionary items where k represents key and v
represents value. The setdefault() method will set newdict[v]=[] and append the key value to list..
As we mentioned earlier, the keys in dictionaries have to hashable. It works correctly only
when keys are immutable. For example, if key is a list and to store a key-value pair Python will hash
the key and store it in corresponding location. If that key is modified, it would be hashed to different
location. In this case, we will have two entries for the same key or might be failed to locate a key.
Either way, the dictionary wouldn’t work correctly. Since lists and dictionaries are mutable, they
can’t be used as keys, but they can be used as values.
For example, consider the recursive version to calculate the Fibonacci numbers. The
following code to compute Fibonacci series has an exponential runtime behavior.
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
The runtime behavior of this recursive version can be improved by adding a dictionary to
memorize previously calculated values of the function.
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
Compound Data: Lists, Tuples, Dictionaries 4.37
return memo[x]
return helper
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
fib = memoize(fib)
print(fib(6)) # output the 6th number in Fibonacci series (series starts from 0th
position)
Sample Output:
8
memoize() takes a function as an argument. The function memorize() uses a dictionary
“memo” to store the function results. Though the variable “memo” as well as the function “f” are
local to memoize, they are captured by a closure through the helper function which is returned as a
reference by memoize(). So, the call memoize(fib) returns a reference to the helper() which is doing
what fib() would do on its own plus a wrapper which saves the calculated results. For an integer ‘n’
fib(n) will only be called, if n is not in the memo dictionary. If it is in it, we can output memo[n] as
the result of fib(n).
memoize
Memo = {}
def helper (x):
if x not in memo:
memo[x]=f(x) Executing;
return memo[x] fib = memoize(fib)
return helper helper is returned
fib
if x not in memo:
if n==0: memo [x]= f(x)
return 0 return memo [x]
elseif n==1:
return 1
else:
return fib(n-1) + fib(n-2)
4.38 Problem Solving and Python Programming
After having executed fib = memoize(fib) fib points to the body of the helper function,
which had been returned by memoize. The decorated Fibonacci function is called in the return
statement return fib(n-1) + fib(n-2), this means the code of the helper function which had been
returned by memorize.
Selection sort algorithm starts by comparing first two elements of an array and swapping if
necessary, i.e., if you want to sort the elements of array in ascending order and if the first element
is greater than second then, you need to swap the elements but, if the first element is smaller than
second, leave the elements as it is. Then, again first element and third element are compared and
swapped if necessary. This process goes on until first and last element of an array is compared.
This completes the first step of selection sort. The working of selection sort algorithm is shown in
Figure.4.3.
20 12 10 15 2 2 20 12 15 10 2 10 20 15 12 2 10 12 20 15
12 20 10 15 2 2 12 20 15 10 2 10 15 20 12 2 10 12 15 20
10 20 12 15 2 2 12 20 15 10 2 10 12 20 15
10 20 12 15 2 2 10 20 15 12
2 20 12 15 10
This algorithm is not suitable for large data sets as its average and worst case complexities
are of Ο(n2), where n is the number of items.
arr=[]
n=input(‘Enter number of elements’)
for i in range(0,n):
x=int(input(‘Enter number’))
arr.insert(i,x)
i+=1
for i in range(len(arr)):
for j in range(i, len(arr)):
Compound Data: Lists, Tuples, Dictionaries 4.39
4.4.2 Python program to sort a list of elements using the insertion sort algorithm
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item
at a time. Here, a sub-list is maintained which is always sorted. The array is searched sequentially and
unsorted items are moved and inserted into the sorted sub-list (in the same array). This algorithm is
suitable for small data sets. But it is much less efficient on large lists than more advanced algorithms
such as quicksort, heapsort, or merge sort. The worst case complexity of the algorithm is of Ο(n2),
where n is the number of items.
Checking second element of array with element
Step 1 12 3 1 5 8 before it and inserting it in proper position. In
this case, 3 is inserted in position of 12.
def insertionsort(list):
for i in range(1,len(list)):
temp=list[i]
4.40 Problem Solving and Python Programming
j=i-1
while temp<+list[j] and j>=0:
list[j+1]=list[j]
j=j-1
list[j+1]=temp
return list
arr=[]
n=input(‘Enter number of elements’)
for i in range(0,n):
x=int(input(‘Enter number’))
arr.insert(i,x)
i+=1
print insertionsort(arr)
Sample input/output:
Enter number of elements5
Enter number12
Enter number23
Enter number4
Enter number16
Enter number34
[4, 12, 16, 23, 34]
4.4.3 Python program to sort a list of elements using the merge sort algorithm
Merge sort is a sorting technique based on divide and conquer technique. It first divides the
array into equal halves and then combines them in a sorted manner. The basic steps involved in
merge sort algorithm are as follows: Given an array A.
1. Divide
If q is the half-way point between p and r, then we can split the subarray A[p..r] into two
arrays A[p..q] and A[q+1, r].
2. Conquer
In the conquer step, we try to sort both the subarrays A[p..q] and A[q+1, r]. If we haven’t yet
reached the base case, we again divide both these subarrays and try to sort them.
Compound Data: Lists, Tuples, Dictionaries 4.41
3. Combine
When the conquer step reaches the base step and we get two sorted subarrays A[p..q] and
A[q+1, r] for array A[p..r], we combine the results by creating a sorted array A[p..r] from
two sorted subarrays A[p..q] and A[q+1, r].
38 27 43 3 9 82 10
38 27 43 3 9 82 10
38 27 43 3 9 82 10
38 27 43 3 9 82 10
27 38 3 43 9 82 10
3 27 38 43 9 10 82
3 9 10 27 38 43 82
def merge_sort(sequence):
if len(sequence) < 2:
return sequence
m = len(sequence) / 2
return merge(merge_sort(sequence[:m]), merge_sort(sequence[m:]))
def merge(left, right):
result = []
i=j=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
4.42 Problem Solving and Python Programming
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
print merge_sort([5, 2, 6, 8, 5, 8, 1])
Sample output:
[1, 2, 5, 5, 6, 8, 8]
4.4.4 Python program to sort a list of elements using the Quick sort algorithm
Like Merge Sort, Quick Sort is a Divide and Conquer algorithm. It picks an element as
pivot and partitions the given array around the picked pivot. The pivot element can be selected using
following different ways.
(1) Always pick first element as pivot.
(2) Always pick last element as pivot.
(3) Pick a random element as pivot.
(4) Pick median as pivot.
The runtime of the algorithm varies based on the pivot selected. The basic idea behind this
algorithm is as follows.
1. Pick one element in the array, which will be the pivot.
2. Make one pass through the array, called a partition step, re-arranging the entries so that:
i) the pivot is in its proper place.
ii) entries smaller than the pivot are to the left of the pivot.
iii) entries larger than the pivot are to its right.
3. Recursively apply quick sort to the part of the array that is to the left of the pivot,
and to the right part of the array.
The steps involved in quick sort algorithm are listed below and can be understand easily
using the example shown in Figure.4.6.
leftmark rightmark
leftmark rightmark
54 26 20 17 77 31 44 55 93 exchange 20 and 93
leftmark rightmark
leftmark rightmark
77 > 54 stop
54 26 20 17 44 31 77 55 93 31 < 54 stop
rightmark < leftmark
split point found
rightmark leftmark exchange 54 and 31
Sample Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
4.4.5 Write a Python program to create a histogram from a given list of integers.
def histogram( items ):
for n in items:
Compound Data: Lists, Tuples, Dictionaries 4.45
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])
Sample Output:
**
***
******
*****
4.46 Problem Solving and Python Programming
Eg:
a=[10, 20, 30]
b=[40, 50]
c=a+b
print c
d=c*2
print d
Output:
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50, 10, 20, 30, 40, 50]
Example:
t1 = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
Whereas, reverse lookup is the process of finding the key for a given value.
print d
Output:
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50, 10, 20, 30, 40, 50]
21. What is the difference between del() and remove() methods of list?
To remove a list element, we can use either the del statement if we know exactly which
element(s) we are deleting or the remove() method if we do not know.
34. How do you create a dictionary which can preserve the order of pairs?
We know that regular Python dictionaries iterate over <key, value> pairs in an
arbitrary order, hence they do not preserve the insertion order of <key, value> pairs.
Python 2.7. introduced a new “OrderDict” class in the “collections” module and it provides the
same interface like the general dictionaries but it traverse through keys and values in an ordered
manner depending on when a key was first inserted.
Eg:
from collections import OrderedDict
d=OrderDict([('Company-id':1),('Company-Name':'Intellipaat')])
d.items() # displays the output as: [('Company-id':1),('Company-Name':'Intellipaat')]
36. How many kinds of sequences are supported by Python? What are they?
Python supports 7 sequence types. They are str, list, tuple, unicode, bytearray, xrange, and
buffer. where xrange is deprecated in python 3.5.X.