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

GE3151 Unit IV

Unit IV covers lists, tuples, and dictionaries in Python, detailing their operations, methods, and advanced processing techniques like list comprehension. It explains how to create, manipulate, and traverse lists, including operations such as indexing, slicing, concatenation, and membership testing. Additionally, it introduces functions like map, filter, and reduce, as well as methods for deleting elements and converting between strings and lists.

Uploaded by

SHEEBA M C CSE
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)
35 views36 pages

GE3151 Unit IV

Unit IV covers lists, tuples, and dictionaries in Python, detailing their operations, methods, and advanced processing techniques like list comprehension. It explains how to create, manipulate, and traverse lists, including operations such as indexing, slicing, concatenation, and membership testing. Additionally, it introduces functions like map, filter, and reduce, as well as methods for deleting elements and converting between strings and lists.

Uploaded by

SHEEBA M C CSE
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

UNIT IV

LISTS, TUPLES, DICTIONARIES

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: simple sorting,
histogram, Students marks statement, Retail bill preparation.

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 elements, 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]

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
>>> a same types
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> b = [1,”a”, 2, “green”, 7] List with values of different
>>> b types
[1, 'a', 2, 'green', 7]
Indexing >>> a[0] Accessing the item in the
2 position 0

>>> a[8] Accessing the item in the


10 position 8

>>> a[-1] Accessing the last element


10 using negative indexing.
Slicing: >>> a[0:3] Printing a part of the list.
[2, 3, 4]
>>> a[0:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Concatenation >>> b = [20,30] Adding and printing the
>>> a + b items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
Repetition >>> b * 3 The * operator repeats a list
[20, 30, 20, 30, 20, 30] a given number of times. It
creates multiple copies of
the same list.
Updating >>> a[2] Updating the list using index
4 value.
>>> a[2] = 100
>>> 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
>>> 5 in a present in list. 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 elements are same.
>>> a == b Otherwise 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:
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.

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.


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

Delimiter:
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.

Syntax
for <item> in <iterable>:
<body>

Eg:
>>> names = ["Neha","John","Mary","Janice","Johan"]
>>> for name in names:
... print("Hi "+ name +"!")
...
Hi Neha!
Hi John!
Hi Mary!
Hi Janice!
Hi Johan!

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] 10
for i in a: 20
print(i) 30
40
50
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.
• 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 = ['Cheddar', 'Edam', 'Gouda']


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


>>> '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
>>> a
[100, 2, 3, 4, 5]
>>> a = [1,2,3,4,5] changing multiple element
>>> a[0:3] = [100,100,100]
>>> a
[100, 100, 100, 4, 5]
>>> a = [1,2,3,4,5] The elements from a list can also be removed
>>> a[0:3] = [ ] by assigning the empty list to them.
>>> a
[4, 5]
>>> a = [1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0] = [20,30,45] squeezing them into an empty slice at the
>>> a desired location.
[20, 30, 45, 1, 2, 3, 4, 5]

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.

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
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 lists 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”
Eg:
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list) [10, 22, 44, 23, 4]
print(new_list) [10, 22, 44, 23, 4]

cloning a list using slice operator


a = [81,56,23]
b = a[:]
print(a == b) True
print(a is b) 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]
print(a is b) False
cloning using List( ) method
a = [1,2,3,4,5]
b = list (a)
print(b) [1, 2, 3, 4, 5]
print(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 reflect
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']

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

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):
for i in range(0,len(a),1):
a[i]=a[i]+10
print("inside",a) inside [11, 12, 13, 14, 15]
a = [1,2,3,4,5]
insidefun(a)
print("outside",a) outside [11, 12, 13, 14, 15]
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
()

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 rang e 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 smarter:

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

More generally, the right side can be any kind of sequence (string, list or tuple). For example,
to split an email address in to 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):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:")) enter a value:4
b=eval(input("enter b value:")) enter b value:3
r,q=div(a,b)
print("reminder:",r) reminder: 1
print("quotient:",q) quotient: 1
Example2: Output:
def min_max(a):
small=min(a)
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small) smallest: 1
print("biggest:",big) biggest: 6

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
Slicing >>> print(a[1:3]) Displaying items from 1st
(40,60) till 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.
True Otherwise
>>> 100 in a returns false
False
>>> 2 not in a
False
Comparison >>> a = (2,3,4,5,6,7,8,9,10) Returns True if all
>>> b = (2,3,4) elements in both are same.
>>> a == b Otherwise
False returns 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:

0 a
1 b
2 c

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:


0 a
1 b
2 c

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
return 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:


0 a
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 = []
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 first
>>> a.index(5) 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()
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']) Jack
print(my_dict.get('age')) 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 is 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) {‘name': 'Jack', 'age': 27}
# add item
my_dict['address'] = 'Downtown'
print(my_dict) {'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)
# 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 dictionary >>> a={1:"one",2:"two"} Creating the dictionary with
>>> print(a) elements of different data
{1: 'one', 2: 'two'} types.
Accessing an element >>> a[1] Accessing the elements by
'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: Returns True if the key is
'three'} present in dictionary.
>>> 1 in a Otherwise returns false.
True
>>> 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
dictionary. here copy of
>>> b=a.copy() dictionary ‘a’ get stored in to
>>> print(b) dictionary ‘b’.
{1: 'ONE', 2: 'two', 3: 'three'}
a.items() >>> a.items() Return a new view of the
dict_items([(1, 'ONE'), (2, 'two'), dictionary's items. It
(3,'three')]) displays a list of dictionaries
(key, value) tuple pairs.
a.keys() >>> a.keys() It displays list of keys in a
dict_keys([1, 2, 3]) 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) with the existing dictionary
>>> print(a)
{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) {'Math': 0, 'English': 0, 'Science': 0}
print(marks) ('Math', 0)
for item in marks.items(): ('English', 0)
print(item) ('Science', 0)
list(sorted(marks.keys()))

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)) 5
print(sorted(squares)) [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 In values can be of any data
nature type and can repeat, keys
must be of immutable type
List are enclosed in brackets Tuples are enclosed in Tuples are enclosed in curly
[ ] and their elements and parenthesis ( ) braces { } and consist of
size can be changed and cannot be updated key:value

Homogenous Heterogeneous Homogenous


Example: Example: Example:
List = [10, 12, 15] Words = ("spam", "egss") Dict = {"ram": 26, "abi":
Or 24}
Words = "spam", "eggs"
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])
Can contain duplicate Can contain duplicate Cant contain duplicate keys,
elements elements. Faster compared but can contain duplicate
to lists 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 • Dictionary is used
collection of data that when data cannot be when a logical association
doesn’t need random access. changed. between key:value pair.
• List is used when • A tuple is used in • When in need of fast
data can be modified combination with a lookup for data, based on a
frequently dictionary i.e. tuple might custom key.
represent a key. • 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) [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']

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)

4.5 ILLUSTRATIVE PROGRAM

Simple Sorting

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
alist=[]
n = int(input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = int(input('Enter the Element %d :' %(i+1)))
alist.append(x)
selectionSort(alist)
print(alist)

Output
Enter Number of Elements in the Array: 9
Enter the Element 1 :26
Enter the Element 2 :54
Enter the Element 3 :93
Enter the Element 4 :17
Enter the Element 5 :77
Enter the Element 6 :31
Enter the Element 7 :44
Enter the Element 8 :55
Enter the Element 9 :20
[17, 20, 26, 31, 44, 54, 55, 77, 93]

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(input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = int(input('Enter the Element %d :' %(i+1)))
alist.append(x)
insertionSort(alist)
print(alist)

Output:
Insertion Sort :
Enter Number of Elements in the Array: 9
Enter the Element 1 :54
Enter the Element 2 :26
Enter the Element 3 :93
Enter the Element 4 :17
Enter the Element 5 :77
Enter the Element 6 :31
Enter the Element 7 :44
Enter the Element 8 :55
Enter the Element 9 :20
[17, 20, 26, 31, 44, 54, 55, 77, 93]

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
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(input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = int(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)

Output
Merge Sort :
Enter Number of Elements in the Array: 9
Enter the Element 1 :54
Enter the Element 2 :26
Enter the Element 3 :93
Enter the Element 4 :17
Enter the Element 5 :77
Enter the Element 6 :31
Enter the Element 7 :44
Enter the Element 8 :55
Enter the Element 9 :20
Original Array :
[54, 26, 93, 17, 77, 31, 44, 55, 20]
Intermediate s :
Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
Splitting [54, 26]
Splitting [54]
Splitting [26]
Splitting [93, 17]
Splitting [93]
Splitting [17]
Merging [17, 26, 54, 93]
Splitting [77, 31, 44, 55, 20]
Splitting [77, 31]
Splitting [77]
Splitting [31]
Splitting [44, 55, 20]
Splitting [44]
Splitting [55, 20]
Splitting [55]
Splitting [20]
Merging [20, 44, 55]
Merging [20, 31, 77, 44, 20]
Merging [20, 31, 77, 44, 55]
Merging [26, 54, 93, 20, 77, 31, 44, 55, 20]
Merging [26, 54, 93, 20, 31, 31, 44, 55, 20]
Merging [26, 54, 93, 20, 31, 77, 44, 55, 20]
Merging [26, 54, 93, 20, 31, 77, 44, 55, 20]
Merging [26, 54, 93, 20, 31, 77, 44, 55, 20]
Sorted Array is:
[26, 54, 93, 20, 31, 77, 44, 55, 20]

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

Splitting

Merging

4.5.4 HISTOGRAM PROGRAM

def histogram(nums):
for x in nums:
output = ''
while x > 0:
output = output + "x"
x=x-1
print(output)

histogram([2, 3, 6, 5])

Explanation

The histogram function loops through a list of numbers (nums) in order: for x in nums with
each number in the list it creates a string (output) containing "x". It then subtracts one from the
number x = x - 1, and joins another "x" to the output string. This continues until the number
reaches a value of 1 when the loop is finished and the number gets printed.
So histogram([2, 3, 6, 5]) would produce:

xx
xxx
xxxxxx
xxxxx

Students marks statement

mark = []
tot = 0
Grade=0
print("Enter Number of Subjects: ")
subNo = int(input())
print("Enter Marks Obtained in " + str(subNo) + " Subjects: ")
for i in range(subNo):
print("Enter Marks Obtained in",i+1,"Subjects: ")
mark.append(input())

for i in range(subNo):
tot = tot + int(mark[i])
avg = tot/subNo

print ("\nThe Total marks is: \t", tot)


print ("\nThe Average marks is: \t", avg)
#print ("\nThe Percentage is: \t", percentage, "%")

if avg==100:
Grade = "O"
elif avg>=90 and avg<=99:
Grade = "A+"
elif avg>=80 and avg<=89:
Grade = "A"
elif avg>=70 and avg<=79:
Grade = "B+"
elif avg>=60 and avg<=69:
Grade = "B"
elif avg>=50 and avg<=59:
Grade = "C"
elif avg>=49 and avg<0:
Grade = "RA"
else:
print("Invalid Input!")
print ("\nThe Grade is: \t", Grade)

output

Enter Number of Subjects:


5
Enter Marks Obtained in 5 Subjects:
Enter Marks Obtained in 1 Subjects:
56
Enter Marks Obtained in 2 Subjects:
67
Enter Marks Obtained in 3 Subjects:
78
Enter Marks Obtained in 4 Subjects:
89
Enter Marks Obtained in 5 Subjects:
90

The Total marks is: 380

The Average marks is: 76.0

The Grade is: B+

You might also like