0% found this document useful (0 votes)
47 views36 pages

GE8151 Unit IV

This document discusses lists in Python. It defines lists as sequences that can contain elements of any data type. It describes how to create, index, slice, concatenate, and perform other operations on lists. It also discusses list methods like append, pop, remove, as well as built-in functions like map, filter and reduce that are commonly used with lists.

Uploaded by

Merbin Jose
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)
47 views36 pages

GE8151 Unit IV

This document discusses lists in Python. It defines lists as sequences that can contain elements of any data type. It describes how to create, index, slice, concatenate, and perform other operations on lists. It also discusses list methods like append, pop, remove, as well as built-in functions like map, filter and reduce that are commonly used with lists.

Uploaded by

Merbin Jose
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
You are on page 1/ 36

1

UNIT IV LISTS, TUPLES, DICTIONARIE


Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension; Illustrative programs: selection sort,
insertion sort, mergesort, histogram.

4.1 Lists
A list is a sequence of values. In a string, the values are characters; in a list, they can be
any type. The values in a list are called elements or sometimes items. There are several ways to
create a new list; the simplest is to enclose the elements in square brackets ([ and ]):

[10, 20, 30, 40] list of four integers


['Apple', Orange, 'Banana'] list of three strings

The elements of a list don‟t have to be the same type. The following list contains a string,
a float, an integer, and another list:
['spam', 2.0, 5, [10, 20]]

A list within another list is called nested list. A list that contains no elements is called an
empty list; we can create one with empty brackets, [].
We can assign list values to variables:

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']


>>> numbers = [42, 123]
>>> empty = []
>>> print(cheeses, numbers, empty)
['Cheddar', 'Edam', 'Gouda'] [42, 123] []
Example: Nested list
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57

4.1.1 List operations


Creating a list:
To create a list, add a number of expressions, separated by comma within a square
bracket.
Syntax:
list_name=[element1, element2, … element n]

Indexing:
An element in the list can be accessed through index operator.
Syntax:
list_name[index] Mr. P. J. Merbin Jose
2
Python allows negative indexing to access the elements. Index -1 refers the last element on the
list, -2 refers the second last element and so on.

Slicing:
List slice is same of string slice. From the list slice we can extract sub part of list based
on user requirements. We can use index values to create a sub list from list.
Syntax:
Var_name=list_name[start value: end value: increment/ decrement step value]

Here start value and end value may be omitted or optional. Default value for start is zero. Default
value for last is last index or -1. Default step value is 1.
Concatenation:
To concatenate or combine two or more lists “+” operator is used.
Repetitions:
Lists can be repeated or repeatedly concatenated with the asterisk operator “*”. The *
operator repeats a list in given number of times.
Membership:
We can determine whether an element is present in the list by using in or not in
operator. The in operator returns true if particular element is present, else it returns false. The
not in operator returns true if particular element is not present, else it returns false.

Operations Examples Description


Create a list >>>a=[2,3,4,5,6,7,8,9,10] Create a list with values of same
>>> print(a) types
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>b[1,”a”, 2, “green”, 7]
List with values of different types
>>> print(a[0]) Accessing the item in the position 0
Indexing 2
>>> print(a[8]) Accessing the item in the position 8
10
>>> print(a[-1]) Accessing the last element using
10 negative indexing.
Slicing: >>> print(a[0:3])
[2, 3, 4]
>>> print(a[0:])
[2, 3, 4, 5, 6, 7, 8, 9, 10] Printing a part of the list.
>>>b=[20,30] Adding and printing the items of
Concatenation >>> print(a+b) two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10,
20, 30]
>>> print(b*3) The * operator repeats a list a given
Repetition [20, 30, 20, 30, 20, 30] number of times. It creates multiple
copies of the same list.
Updating >>> print(a[2]) Updating the list using index value.
4
Mr. P. J. Merbin Jose
3
>>> a[2]=100
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Membership >>> a=[2,3,4,5,6,7,8,9,10] Returns True if element is present in
>>> 5 in a list. Otherwise returns false.
True
>>> 100 in a
False
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10] Returns True if all elements in both
Comparison >>>b=[2,3,4] elements are same. Otherwise
>>> a==b returns false
False
>>> a!=b
True

Map, filter and reduce


Most common list operations can be expressed as a combination of map, filter and
reduce.
To add up all the numbers in a list, we can use a loop like this:
def add_all(t):
total = 0
for x in t:
total += x
return total

Here total is initialized to 0. Each time through the loop, x gets one element from the list. The +=
operator provides a short way to update a variable. This augmented assignment statement,
total += x
is equivalent to
total = total + x
As the loop runs, total accumulates the sum of the elements; a variable used this way is
sometimes called an accumulator.

Reduce - that combines a sequence of elements into a single value


Adding up the elements of a list is such a common operation that Python provides it as a
built-in function, sum:
>>> t = [1, 2, 3]
>>> sum(t)
6
An operation like this which combines a sequence of elements into a single value is sometimes
called reduce.

Map -“maps” a function onto each of the elements in a sequence.


Example: Function takes a list of strings and returns a new list that contains capitalized strings:
def capitalize_all(t):
res = []
for s in t:

Mr. P. J. Merbin Jose


4
res.append(s.capitalize())
return res
Here „res‟ is initialized with an empty list; each time through the loop, we append the
next element. So „res‟ is another kind of accumulator.
An operation like capitalize_all is sometimes called a map because it “maps” a function
(in this case the method capitalize) onto each of the elements in a sequence.

Filter - select some of the elements from a list and return a sublist
Example: Function takes a list of strings and returns a list that contains only the uppercase
strings:
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
return res

Here „isupper‟ is a string method that returns True if the string contains only upper case letters.
An operation like only_upper is called a filter because it selects some of the elements and filters
out the others.

Deleting elements
There are several ways to delete elements from a list.
 If we know the index of the element, we can use pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> t
['a', 'c']
>>> x
'b'

pop modifies the list and returns the element that was removed.
 If an index is not given, it deletes and returns the last element.
 If we don‟t need the removed value, we can use the del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> t
['a', 'c']

 If you know the element we want to remove (but not the index), we can use remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> t
['a', 'c']
The return value from remove is None.
 To remove more than one element, we can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> t
['a', 'f']
As usual, the slice selects all the elements up to but not including the second index.
5
4.1.2 List slices
List slicing is an operation that extracts a subset of elements from a list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]

The default start value is 0 and default stop value is n-1.


>>> t = ['a', 'b', 'c', ‟d‟, 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']

If we omit the first index, the slice starts at the beginning. If we omit the second, the slice goes to
the end. So if we omit both, the slice is a copy of the whole list. i.e [:] this will print the entire list

>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
[2:2] this will create an empty slice.

>>> a[2:2]
[]
>>> a=[9,8,7,6,5,4]
>>> a[0:6:2]
[9, 7, 5]
>>> a[0:6:3]
[9,6]

Since lists are mutable, it is often useful to make a copy before performing operations that
modify lists.
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> t
['a', 'x', 'y', 'd', 'e', 'f']

4.1.3 List methods


Python provides methods that operate on lists.

Syntax
Listname.methodname(element/index/list)

Syntax Example Description


a.append(element) >>> a=[1,2,3,4,5] Add an element to the end of
>>> a.append(6) the list
>>> print(a)
[1, 2, 3, 4, 5, 6]
>>> t = ['a', 'b', 'c']
6
>>> t.append('d')
>>> t
['a', 'b', 'c', 'd']
a.insert(index,element) >>> a.insert(0,0) Insert an item at the defined
>>> print(a) index
[0, 1, 2, 3, 4, 5, 6]

a.extend(b) >>> b=[7,8,9] Takes a list as an argument


>>> a.extend(b) and appends all of the
>>> print(a) elements to another list.
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> t1
['a', 'b', 'c', 'd', 'e']
a.index(element) >>> a.index(8) Returns the index of the first
8 matched item
>>>t1.index(„b‟)
1
a.sort() >>> a.sort() Sort items in a list in
>>> print(a) ascending order
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> t
['a', 'b', 'c', 'd', 'e']
a.reverse() >>> a.reverse() Reverse the order of items in
>>> print(a) the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]
a.pop() >>> a.pop() Removes and returns an
0 element at the last element
a.pop(index) >>> a.pop(0) Remove the particular element
8 and return it.
a.remove(element) >>> a.remove(1) Removes an item from the list
>>> print(a)
[7, 6, 5, 4, 3, 2]
a.count(element) >>> a.count(6) Returns the count of number
1 of items passed as an argument
a.copy() >>> b=a.copy() Returns a shallow copy of the
>>> print(b) list
[7, 6, 5, 4, 3, 2]
len(list) >>> len(a) Returns the length of the
6 length
min(list) >>> min(a) Returns the minimum element
2 in a list
max(list) >>> max(a) Returns the maximum element
7 in a list.
a.clear() >>> a.clear() Removes all items from the
>>> print(a) [ ] list.
del(a) >>> del(a) Deletes the entire list.
7
>>> print(a)
Error: name 'a' is not defined

Lists and strings


A string is a sequence of characters and a list is a sequence of values, but a list of
characters is not the same as a string.
List:
To convert from a string to a list of characters, we can use list:
>>> s = 'spam'
>>> t = list(s)
>>> t
['s', 'p', 'a', 'm']
The list function breaks a string into individual letters.

Split:
If we want to break a string into words, we can use the split method:
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> t
['pining', 'for', 'the', 'fjords']

An optional argument called a delimiter specifies which characters to use as word boundaries.
The following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> t = s.split(delimiter)
>>> t
['spam', 'spam', 'spam']
Join
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string
method, so we have to invoke it on the delimiter and pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> s = delimiter.join(t)
>>> s
'pining for the fjords'
In this case the delimiter is a space character, so join puts a space between words. To concatenate
strings without spaces, we can use the empty string, '', as a delimiter.

4.1.4 List Loop


In Python, lists are considered a type of iterable. An iterable is a data type that can return
its elements separately, i.e., one at a time.

Traversing a list
List using for loop:
The most common way to traverse the elements of a list is with a „for‟ loop.
 The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
 Iterating over a sequence is called traversal.
 Loop continues until we reach the last item in the sequence.
8
Syntax
for <item> in <iterable>:
<body>
Eg:
>>>names = ["Neha","John","Mary","Janice","Johan"]
>>>for name in names:
...print("Hi "+ name +"!")

 To read the elements of the list:


for cheese in cheeses:
print(cheese)
 To write or update the elements of the list, combine the built-in functions range and len
as below:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2

This loop traverses the list and updates each element. len returns the number of elements
in the list. range returns a list of indices from 0 to n - 1, where n is the length of the list. Each
time through the loop i gets the index of the next element. The assignment statement in the body
uses i to read the old value of the element and to assign the new value.
 A for loop over an empty list never runs the body:
for x in []:
print('This never happens.')
Although a list can contain another list, the nested list still counts as a single element. The length
of this list is four: ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]

Accessing element Output


a=[10,20,30,40,50] 1
for i in a: 2
print(i) 3
4
5
Accessing index Output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range: Output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
50

List using While loop


 The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
9
 When the condition is tested and the result is false, the loop body will be skipped and
the first statement after the while loop will be executed.
Syntax:
while (condition):
body of while

Example: Sum of elements in list


a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

Output: 15

4.1.5 Mutability:
 Lists are mutable. (can be changed)
 Mutability is the ability for certain types of data to be changed without entirely recreating
it.
 An item can be changed in a list by accessing it directly as part of the assignment
statement.
 Using the indexing operator (square brackets[ ]) on the left side of an assignment, one of
the list items can be updated.

The syntax for accessing the elements of a list is the same as for accessing the characters
of a string—the bracket operator. The expression inside the brackets specifies the index.
Remember that the indices start at 0:
>>> cheeses[0]
'Cheddar'

Unlike strings, lists are mutable. When the bracket operator appears on the left side of an
assignment, it identifies the element of the list that will be assigned.
>>> numbers = [42, 123]
>>> numbers[1] = 5
>>> numbers
[42, 5]

The one-eth element of numbers, which used to be 123, is now 5.

List indices work the same way as string indices:


 Any integer expression can be used as an index.
 If we try to read or write an element that does not exist, we get an IndexError.
 If an index has a negative value, it counts backward from the end of the list.

The in operator also works on lists.


>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
10
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

Figure below shows the state diagram for cheeses, numbers and empty:

Example Description
>>> a=[1,2,3,4,5] changing single element
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
>>> a=[1,2,3,4,5] changing multiple element
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can
>>> a[0:3]=[ ] also be removed by assigning
>>> print(a) the empty list to them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted
>>>a[0:0]=[20,30,45] into a list by squeezing them
>>> print(a) into an empty slice at the
[20,30,45,1, 2, 3, 4, 5] desired location.

Objects and values


If we run these assignment statements:
a = 'banana'
b = 'banana'
We know that a and b both refer to a string, but we don‟t know whether they refer to the same
string. There are two possible states, shown in Figure.

Fig: State Diagram


In one case, a and b refer to two different objects that have the same value. In the second case,
they refer to the same object.
To check whether two variables refer to the same object, we can use the is operator.
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
11
In this example, Python only created one string object, and both a and b refer to it. But when we
create two lists, we get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
So the state diagram looks like,

In this case we would say that the two lists are equivalent, because they have the same
elements, but not identical, because they are not the same object. If two objects are identical,
they are also equivalent, but if they are equivalent, they are not necessarily identical.

4.1.6 Aliasing
Creating a copy of a list is called aliasing. When we create a copy both list will be having
same memory location. Changes in one list will affect another list. Aliasing refers to having
different names for same list values.
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
The state diagram looks like,

The association of a variable with an object is called a reference. In this example, 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.

If the aliased object is mutable, changes made with one alias affect the other. When the
first element of the list named “a” is replaced, the first element of the list named “b” is also
replaced.
>>> b[0] = 42
>>> a
[42, 2, 3]

This type of change is known as a side effect. This happens because after the assignment
b=a, the variables a and b refer to the exact same list object. They are aliases for the same object.
This phenomenon is known as aliasing. To prevent aliasing, a new object can be created and the
contents of the original can be copied which is called cloning.

4.1.8 List cloning


To avoid the disadvantages of copying we are using cloning. If we want to modify a list
and also keep a copy of the original, we need to be able to make a copy of the list itself, not just
the reference. This process is sometimes called cloning, to avoid the ambiguity of the word copy.
i.e creating a copy of a same list of elements with two different memory locations is called
cloning. Cloning means making an exact but separate copy i.e., create a new list and copy every
element. Changes in one list will not affect locations of another list.
“Cloning is a process of making a copy of the list without modifying the original list”
12
Eg:
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)

Output: [10, 22, 44, 23, 4]


[10, 22, 44, 23, 4]

cloning a list using slice operator


a=[81,56,23] #Output
b=a[:]
print(a == b) #True True
print a is b # False False
b[0] = 5
print(a) [81,56,23]
print(b) [5,56,23]
cloning using copy() method
a=[1,2,3,4,5]
b=a.copy()
print(b) [1, 2, 3, 4, 5]
a is b False
cloning using List( ) method
a=[1,2,3,4,5]
b=list (a)
print(b) [1,2,3,4,5]
a is b False
a[0]=100
print(a) [100,2,3,4,5]
print(b) [1,2,3,4,5]

4.1.9 List arguments (parameters)

In python, arguments are passed by reference. When we pass a list to a function, the
function gets a reference to the list. If the function modifies the list, the caller sees the change. If
any changes are done in the parameter which refers within the function, then the changes also
reflects back in the calling function.
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change the
same list that the argument is referencing.
For example, delete_head removes the first element from a list:
def delete_head(t):
del t[0]

Here‟s how it is used:


>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> letters
['b', 'c']
13
The parameter t and the variable letters are aliases for the same object. The state diagram looks
like,

It is important to distinguish between operations that modify lists and operations that create new
lists. For example, the append method modifies a list, but the + operator creates a new list.

Here‟s an example using append:


>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> t1
[1, 2, 3]
>>> t2
None
The return value from append is None.

Here‟s an example using the + operator:


>>> t3 = t1 + [4]
>>> t1
[1, 2, 3]
>>> t3
[1, 2, 3, 4]

The result of the operator is a new list, and the original list is unchanged.
For example, this function does not delete the head of a list:

def bad_delete_head(t):
t = t[1:]
The slice operator creates a new list and the assignment makes t refer to it, but that doesn‟t affect
the caller.
>>> t4 = [1, 2, 3]
>>> bad_delete_head(t4)
>>> t4
[1, 2, 3]

At the beginning of bad_delete_head, t and t4 refer to the same list. At the end, t refers to a new
list, but t4 still refers to the original, unmodified list.

An alternative is to write a function that creates and returns a new list. For example, tail returns
all from the first element of a list:
def tail(t):
return t[1:]

This function leaves the original list unmodified. Here‟s how it is used:
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> rest
['b', 'c']
14
Example 1: Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Example 2: Output
def insidefun(a): inside [11, 12, 13, 14, 15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
insidefun(a)
print(“outside”,a)
Example 3: Output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)

4.2 TUPLES

Tuples are immutable


A tuple is a sequence of values. The values can be any type, and they are indexed by
integers, so in that respect tuples are a lot like lists. The important difference is that tuples are
immutable. That is once a tuple is defined, it cannot be altered. Syntactically, a tuple is a
comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'

Although it is not necessary, it is common to enclose tuples in parentheses:


>>> t = ('a', 'b', 'c', 'd', 'e')

To create a tuple with a single element, we have to include a final comma:


>>> t1 = 'a',
>>> type(t1)
<type 'tuple'>

A value in parentheses is not a tuple:


>>> t2 = ('a')
>>> type(t2)
<type 'str'>

Another way to create a tuple is the built-in function tuple. With no argument, it creates an
empty tuple:
>>> t = tuple()
>>> print t
()
15
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the
sequence:
>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')

Because tuple is the name of a built-in function, we should avoid using it as a variable
name. Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'

And the slice operator selects a range of elements.


>>> print t[1:3]
('b', 'c')

But if we try to modify one of the elements of the tuple, we get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment

we can‟t modify the elements of a tuple, but we can replace one tuple with another:
>>> t = ('A',) + t[1:]
>>> print t
('A', 'b', 'c', 'd', 'e')

Benefits of Tuple:
 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.

4.2.1 Tuple assignment


It is often useful to swap the values of two variables. With conventional assignments, we
have to use a temporary variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
But tuple assignment is more smart:
>>> a, b = b, a
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.
The number of variables on the left and the number of values on the right have to be the
same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
16
More generally, the right side can be any kind of sequence (string, list or tuple). For
example, to split an email address into a user name and a domain, we could write:
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')

The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain
>>> print uname
monty
>>> print domain
python.org

4.2.2 Tuples as return values


A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values. For example, if we want to divide two integers and compute the
quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute
them both at the same time.
The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and remainder. We can store the result as a tuple:
>>> t = divmod(7, 3)
>>> print t
(2, 1)

Or use tuple assignment to store the elements separately:


>>> quot, rem = divmod(7, 3)
>>> print quot
2
>>> print rem
1
Here is an example of a function that returns a tuple:
def min_max(t):
return min(t), max(t)

max and min are built-in functions that find the largest and smallest elements of a sequence.
min_max computes both and returns a tuple of two values.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
17
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)

Variable-length argument tuples


Functions can take a variable number of arguments. A parameter name that begins with *
gathers arguments into a tuple. For example, printall takes any number of arguments and prints
them:
def printall(*args):
print args

The gather parameter can have any name we like, but args is conventional. Here‟s how the
function works:
>>> printall(1, 2.0, '3')
(1, 2.0, '3')
The complement of gather is scatter. If we have a sequence of values and we want to
pass it to a function as multiple arguments, we can use the * operator. For example, divmod takes
exactly two arguments; it doesn‟t work with a tuple:
>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1

But if we scatter the tuple, it works:


>>> divmod(*t)
(2, 1)
>>> max(1,2,3)
3
But sum does not.
>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3
Write a function called sumall that takes any number of arguments and returns their sum.
Summary of operations on tuples:
Operations Examples Description
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) Create tuple with elements of
different datatype
Indexing >>>print(a[0]) Accessing the item in the
20 position 0
>>> a[2] Accessing the item in the
60 position 2
18
Slicing >>>print(a[1:3]) Displaying items from 1st till
(40,60) 2nd
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) Repeating the tuple in n
(2,4,2,4) number of times

Membership >>> a=(2,3,4,5,6,7,8,9,10) Returns True if element is


>>> 5 in a present in tuple. Otherwise
True returns false
>>> 100 in a
False
>>> 2 not in a
False
Comparison >>> a=(2,3,4,5,6,7,8,9,10) Returns True if all elements
>>>b=(2,3,4) in both are same. Otherwise
>>> a==b returns false
False
>>> a!=b
True

Lists and tuples


zip is a built-in function that takes two or more sequences and “zips” them into a list of
tuples where each tuple contains one element from each sequence. In Python 3, zip returns an
iterator of tuples, but for most purposes, an iterator behaves like a list.
This example zips a string and a list:
>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a', 0), ('b', 1), ('c', 2)]

The result is a list of tuples where each tuple contains a character from the string and the
corresponding element from the list.

If the sequences are not the same length, the result has the length of the shorter one.
>>> zip('Anne', 'Elk') [('A', 'E'), ('n', 'l'), ('n', 'k')]

We can use tuple assignment in a for loop to traverse a list of tuples:


t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print number, letter

Each time through the loop, Python selects the next tuple in the list and assigns the elements to
letter and number. The output of this loop is:
0a
1b
19
2c
If we combine zip, for and tuple assignment, we get a useful idiom for traversing two (or
more) sequences at the same time. For example, has_match takes two sequences, t1 and t2, and
returns True if there is an index i such that t1[i] == t2[i]:
def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False

If we need to traverse the elements of a sequence and their indices, we can use the built-in
function enumerate:
for index, element in enumerate('abc'):
print index, element

The output of this loop is:


0a
1b
2c

Dictionaries and tuples


Dictionaries have a method called items that returns a list of tuples, where each tuple is a
key-value pair.
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]
As we should expect from a dictionary, the items are in no particular order. In Python3,
items returns an iterator, but for many purposes, iterators behave like lists. Going in the other
direction, we can use a list of tuples to initialize a new dictionary:
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}

Combining dict with zip yields a concise way to create a dictionary:


>>> d = dict(zip('abc', range(3)))
>>> print d
{'a': 0, 'c': 2, 'b': 1}

The dictionary method update also takes a list of tuples and adds them, as key-value
pairs, to an existing dictionary. Combining items, tuple assignment and for, we get the idiom for
traversing the keys and values of a dictionary:
for key, val in d.items():
print val, key
The output of this loop is:
20
0a
2c
1b
It is common to use tuples as keys in dictionaries (primarily because we can‟t use lists).
For example, a telephone directory might map from last-name, first-name pairs to telephone
numbers. Assuming that we have defined last, first and number, we could write:
directory[last,first] = number
The expression in brackets is a tuple. We could use tuple assignment to traverse this
dictionary.

for last, first in directory:


print first, last, directory[last,first]

This loop traverses the keys in directory, which are tuples. It assigns the elements of each tuple
to last and first, then prints the name and corresponding telephone number. There are two ways
to represent tuples in a state diagram. The more detailed version shows the indices and elements
just as they appear in a list.

Comparing tuples
The relational operators work with tuples and other sequences; Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the next
elements, and so on, until it finds elements that differ. Subsequent elements are not considered
(even if they are really big).
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
The sort function works the same way. It sorts primarily by first element, but in the case
of a tie, it sorts by second element, and so on. This feature lends itself to a pattern called DSU for
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.
For example, suppose you have a list of words and you want to sort them from longest to
shortest:

def sort_by_length(words):
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
21
for length, word in t:
res.append(word)
return res

The first loop builds a list of tuples, where each tuple is a word preceded by its length.
sort compares the first element, length, first, and only considers the second element to break ties.
The keyword argument reverse=True tells sort to go in decreasing order.
The second loop traverses the list of tuples and builds a list of words in descending order of
length.

Tuple Methods
Methods Example Description
a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> a.count(3) given element.
1
len(tuple) >>> len(a) return the length of the
5 Tuple
min(tuple) >>>min(a) return the minimum element
1 in a Tuple
max(tuple) >>>max (a) return the maximum element
5 in a Tuple
del(tuple) >>>del (a) Delete the entire tuple

4.3 DICTIONARY
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair.

4.3.1 Operations
How to create a dictionary?
Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma.
An item has a key and the corresponding value expressed as a pair, key: value. While
values can be of any data type and can repeat, keys must be of immutable type (string, number or
tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
We can also create a dictionary using the built-in function dict().
# using dict()
22
my_dict = dict({1:'apple', 2:'ball'})
How to access elements from a dictionary?
While indexing is used with other container types to access values, dictionary uses keys.
Key can be used either inside square brackets or with the get() method.
The difference while using get() is that it returns None instead of KeyError, if the key is
not found.
my_dict = {'name':'Jack', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))

OUTPUT: Jack
26
# Trying to access keys which doesn't exist throws error
>>>my_dict.get('address')
>>>my_dict['address']
#Error:

How to change or add elements in a dictionary?


Dictionary are mutable. We can add new items or change the value of existing items
using assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
Output:
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

How to delete or remove elements from a dictionary?


We can remove a particular item in a dictionary by using the method pop(). This method
removes as item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value)
form the dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary
itself.
Commands Output
# create a dictionary {1:1, 2:4, 3:9, 4:16, 5:25}
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares)
23
# remove a particular item 16
print(squares.pop(4))
print(squares) {1: 1, 2: 4, 3: 9, 5: 25}
# remove an arbitrary item (1, 1)
print(squares.popitem())
print(squares) {2: 4, 3: 9, 5: 25}
# delete a particular item {2: 4, 3: 9}
del squares[5]
print(squares)
# remove all items {}
squares.clear()
print(squares)
# delete the dictionary itself # Throws Error
del squares
print(squares)
Summary of operations in Dictionary
Operations Example Description
Creating a >>> a={1:"one",2:"two"} Creating the dictionary with
dictionary >>> print(a) elements of different data
{1: 'one', 2: 'two'} types.
Accessing an >>> a[1] Accessing the elements by
element 'one' using keys.
>>> a[0]
KeyError: 0
Update >>> a[1]="ONE" Assigning a new value to
>>> print(a) key. It replaces the old value
{1: 'ONE', 2: 'two'} by new value.
Add element >>> a[3]="three" Add new element in to the
>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}
Membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is
>>> 1 in a present in dictionary.
True Otherwise returns false.
>>> 3 not in a
False

4.3.2 Python Dictionary Methods


Some methods that are available with dictionary are tabulated below.
Method Example Description

a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the


>>> b=a.copy() dictionary. here copy of
>>> print(b) dictionary ‟a‟ get stored
in to dictionary „b‟
{1: 'ONE', 2: 'two', 3: 'three'}
24
a.items() >>> a.items() Return a new view of the
dict_items([(1, 'ONE'), (2, 'two'), (3,'three')]) dictionary's items. It
displays a list of dictionary‟s
(key, value) tuple pairs.
a.keys() >>> a.keys() It displays list of keys in
dict_keys([1, 2, 3]) a dictionary
a.values() >>> a.values() It displays list of values in
dict_values(['ONE', 'two', 'three']) dictionary
a.pop(key) >>> a.pop(3) Remove the element with
'three' key and return its value from
>>> print(a) the dictionary.
{1: 'ONE', 2: 'two'}
setdefault(key,value) >>> a.setdefault(3,"three") If key is in the dictionary,
'three' return its value. If key is not
>>> print(a) present, insert key with a
{1: 'ONE', 2: 'two', 3: 'three'} value of dictionary and
>>> a.setdefault(2) return dictionary.
'two'
a.update(dictionary) >>> b={4:"four"}
It will add the dictionary
>>> a.update(b)
>>> print(a) with the existing dictionary
{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'}
fromkeys() >>> key={"apple","ball"} It creates a dictionary from
>>> value="for kids" key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}
len(a) a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of the
>>>lena(a) list.
3
clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements form
>>>a.clear() the dictionary.
>>>print(a)
>>>{ }
del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire
>>> del(a) dictionary.

Example:
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
for item in marks.items():
print(item)
list(sorted(marks.keys()))
Output:
25
{'English': 0, 'Math': 0, 'Science': 0}
('English', 0)
('Math', 0)
('Science', 0)
['English', 'Math', 'Science']

Built-in Functions with Dictionary


Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used with
dictionary to perform different tasks.

Function Description
all() Return True if all keys of the dictionary are true (or if the
dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary
is empty, return False.
len() Return the length (the number of items) in the dictionary.
cmp() Compares items of two dictionaries.
sorted() Return a new sorted list of keys in the dictionary.

Here are some examples that uses built-in functions to work with dictionary.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(len(squares))
print(sorted(squares))
Output:
5
[1, 3, 5, 7, 9]
Difference between List, Tuples and dictionary:

List Tuples Dictionary


A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are fixed size in nature In values can be of any
data type and can
repeat, keys must be of
immutable type
List are enclosed in Tuples are enclosed in parenthesis ( ) Tuples are enclosed in
brackets[ ] and their and cannot be updated curly braces { } and
elements and size consist of key:value
can be changed
Homogenous Heterogeneous Homogenous
Example: Example: Example:
List = [10, 12, 15] Words = ("spam", "egss") Dict = {"ram": 26, "abi":
Or 24}
Words = "spam", "eggs"
26
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])
Can contain duplicate Can contain duplicate elements. Cant contain duplicate
elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
 List is used if a  Tuple can be used when data  Dictionary is used
collection of data that cannot be changed. when a logical association
doesn‟t need random between key:value pair.
 A tuple is used in combination
access.  When in need of fast
with a dictionary i.e.a tuple
 List is used when lookup for data, based on a
might represent a key.
data can be modified custom key.
frequently  Dictionary is used
when data is being
constantly modified

4.4 ADVANCED LIST PROCESSING


4.4.1 List Comprehension
List comprehension is an elegant and concise way to create new list from an existing list
in Python. List comprehension consists of an expression followed by for statement inside square
brackets.
Syntax
list=[ expression for item in list if conditional ]

Here is an example to make a list with each item being increasing power of 2.
pow2 = [2 ** x for x in range(10)]
print(pow2)
Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
This code is equivalent to
pow2 = []
for x in range(10):
pow2.append(2 ** x)

A list comprehension can optionally contain more for or if statements. An optional if statement
can filter out items for the new list.
Here are some examples.
>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']] ['Python
Language', 'Python Programming', 'C Language', 'C Programming']
27
List Comprehension Output
>>>L=[x**2 for x in range(0,5)] [0, 1, 4, 9, 16]
>>>print(L)
>>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
>>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i']
>>>mixed=[1,2,"a",3,4.2] [1, 4, 9]
>>> [x**2 for x in mixed if type(x)==int]
>>>[x+3 for x in [1,2,3]] [4, 5, 6]
>>> [x*x for x in range(5)] [0, 1, 4, 9, 16]
>>> num=[-1,2,-3,4,-5,6,-7] [2, 4, 6]
>>> [x for x in num if x>=0]
>>> str=["this","is","an","example"] ['t', 'i', 'a', 'e']
>>> element=[word[0] for word in str]
>>> print(element)

Programs on matrix:
Matrix addition Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)
Matrix multiplication Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
for k in range(len(b)):
c[i][j]=a[i][j]+a[i][k]*b[k][j]
for i in c:
print(i)
Matrix transpose Output
a=[[1,3],[1,2]] [1, 1]
c=[[0,0],[0,0]] [3, 2]
for i in range(len(a)):
for j in range(len(a)):
c[i][j]=a[j][i]
for i in c:
print(i)
28
4.5 ILLUSTRATIVE PROGRAM

4.5.1 Selection Sort


The algorithm divides the input list into two parts: the sublist of items already sorted,
which is built up from left to right at the front (left) of the list, and the sublist of items remaining
to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted
sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest,
depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the
leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one
element to the right.

#Python Program to sort the elements using Selection Sort


def selectionSort(alist):
for i in range(len(alist)-1,0,-1):
positionOfMax=0
for location in range(1,i+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location
temp = alist[i]
alist[i] = alist[positionOfMax]
alist[positionOfMax] = temp

n = int(raw_input('Enter Number of Elements in the Array: '))


for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
alist.append(x)
29
selectionSort(alist)
print(alist)

4.5.2 Insertion Sort


Insertion sort iterates, consuming one input element each repetition, and growing a sorted
output list. At each iteration, insertion sort removes one element from the input data, finds the
location it belongs within the sorted list, and inserts it there. It repeats until no input elements
remain.
Sorting is typically done in-place, by iterating up the array, growing the sorted list behind
it. At each array-position, it checks the value there against the largest value in the sorted list
(which happens to be next to it, in the previous array-position checked). If larger, it leaves the
element in place and moves to the next. If smaller, it finds the correct position within the sorted
list, shifts all the larger values up to make a space, and inserts into that correct position.
The resulting array after k iterations has the property where the first k + 1 entries are
sorted ("+1" because the first entry is skipped). In each iteration, the first remaining entry of the
input is removed, and inserted into the result at the correct position, thus extending the result:

becomes

with each element greater than x copied to the right as it is compared against x.

#Python Program to sort the elements using Insertion Sort


def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue

alist = []
print('Insertion Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
alist.append(x)
insertionSort(alist)
print(alist)

Output:
#For example alist = [54,26,93,17,77,31,44,55,20]
[17, 20, 26, 31, 44, 54, 55, 77, 93]
30
Example

The following figure shows the fifth pass in detail. At this point in the algorithm, a sorted sublist
of five items consisting of 17, 26, 54, 77, and 93 exists. We want to insert 31 back into the
already sorted items. The first comparison against 93 causes 93 to be shifted to the right. 77 and
54 are also shifted. When the item 26 is encountered, the shifting process stops and 31 is placed
in the open position. Now we have a sorted sublist of six items.

4.5.3 Merge Sort


Merge sort is a recursive algorithm that continually splits a list in half. If the list is
empty or has one item, it is sorted by definition (the base case). If the list has more than one
item, we split the list and recursively invoke a merge sort on both halves. Once the two halves
are sorted, the fundamental operation, called a merge, is performed. Merging is the process of
taking two smaller sorted lists and combining them together into a single, sorted, new list.

#Python Program to sort the elements using Merge Sort


def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
31
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if int(lefthalf[i]) < int(righthalf[j]):
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
data = []
print('Merge Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate s :')
mergeSort(data)
print('Sorted Array is:')
print(data)

The following figure shows how the list as it is being sorted by merge sort.
Splitting
32
Merging

4.5.4 HISTOGRAM PROGRAM


def histogram( items ):
for n in items:
output = ' '
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])

Output:
**
***
******
*****

Additional programs:
1. Python program to find the factorial of a number.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

2. Python program to find the factorial of a number using recursion.


def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
33
num = int(input("Enter a number: "))
# check is the number is negative
if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))

3. Python program to check if the input number is prime or not


num = int(input("Enter a number: "))
#prime numbers are greater than 1
if num> 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than or equal to 1, it is not prime
else:
print(num,"is not a prime number")

4. Program to display the Fibonacci sequence up to nth term


nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0
# check if the number of terms is valid
if nterms<= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count <nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth count += 1
34
5. Python Program to Check Armstrong number
num =(input("Enter first number: "))
#Changed num variable to string, and calculated the length (number of digits)
order = len(str(num))
#initialize sum
sum = 0
#find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
#display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

6. Program to add two matrices using nested loop

X = [[12,7,3],[4 ,5,6],[7 ,8,9]]


Y = [[5,8,1],[6,7,3],[4,5,9]]
result = [[0,0,0],[0,0,0],[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)

7. Program to multiply two matrices using nested loops


# 3x3 matrix
X = [[12,7,3], [4 ,5,6],[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]]
result = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
Mr. P. J. Merbin Jose
35
8. Program to transpose a matrix using nested loop
X = [[12,7], [4 ,5], [3 ,8]]
result = [[0,0,0], [0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)

9. Program to sort alphabetically the words from a string provided by the user

my_str = input("Enter a string: ")


words = my_str.split() #breakdown the string into a list of words
words.sort() #sort the list
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)

10. Calendar program

import calendar
y=int(input("enter year:"))
m=int(input("enter month:"))
print(calendar.month(y,m))

Question bank
PART – A

1. What is slicing?
2. How can we distinguish between tuples and lists?
3. What will be the output of the given code?
a. List=[„p‟,‟r‟,‟i‟,‟n‟,‟t‟,]
b. print List[2:]
4. Give the syntax required to convert an integer number into string?
5. List is mutable. Justify?
6. Difference between del and remove methods in List?
7. Difference between pop and remove in list?
8. How are the values in a tuple accessed?
9. What is a Dictionary in Python?
10. Define list comprehension.
11. Write a python program using list looping.
12. What do you meant by mutability and immutability?
13. Define Histogram.
14. Define Tuple and show it is immutable with an example.
15. State the difference between aliasing and cloning in list
16. What is list cloning?
17. What is deep cloning?
Mr. P. J. Merbin Jose
36
18. State the difference between pop and remove method in list.
19. Create tuple with single element.
20. Swap two numbers without using third variable.
21. Define properties of key in dictionary.
22. How can you access elements from the dictionary?
23. Difference between delete and clear method in dictionary.
24. What is squeezing in list? Give an example.
25. How to convert a tuple in to list?
26. How to convert a list in to tuple?
27. Create a list using list comprehension.
28. Advantage of list comprehension.
29. What is the use of map () function?
30. How can you return multiple values from function?
31. What is sorting and types of sorting?
32. Find length of sequence without using library function.
33. How to pass tuple as argument?
34. How to pass a list as argument?
35. What is parameter and types of parameter?
36. How can you insert values in to dictionary?
37. What is key value pair?
38. Mention different data types can be used in key and value.
39. What are the immutable data types available in python?
40. What is the use of fromkeys() in dictioanary?

PART-B
1. Explain in details about list methods.
2. Discuss about operations in list.
3. What is cloning? Explain it with example.
4. What is aliasing? Explain with example.
5. How can you pass list into function? Explain with example.
6. Explain tuples as return values with examples.
7. Write a program for matrix multiplication.
8. Write a program for matrix addition.
9. Write a program for matrix subtraction.
10. Write a program for matrix transpose.
11. Write procedure for selection sort.
12. Explain merge sort with an example.
13. Explain insertion with example.
14. Explain in detail about dictionaries and its methods.
15. Explain in detail about advanced list processing

Mr. P. J. Merbin Jose

You might also like