0% found this document useful (0 votes)
16 views

UNIT IV (1)

This document provides an overview of lists in Python, detailing their structure, access methods, and various operations such as concatenation, repetition, slicing, and built-in methods. It explains how to manipulate lists using methods like append, insert, remove, and sort, as well as the concept of list mutability and aliasing. Additionally, it includes examples to illustrate the functionality of lists and their methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

UNIT IV (1)

This document provides an overview of lists in Python, detailing their structure, access methods, and various operations such as concatenation, repetition, slicing, and built-in methods. It explains how to manipulate lists using methods like append, insert, remove, and sort, as well as the concept of list mutability and aliasing. Additionally, it includes examples to illustrate the functionality of lists and their methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT IV

LIST, TUPLES, DICTIONARIES

4.1. Lists

The list is a most versatile datatype available in Python which can be


written as a list of comma-separated values (items) between square brackets.
Important thing about a list is that items in a list need not be of the same
type. Python offers a range of compound datatypes often referred to as
sequences.
List is one of the most frequently used and very versatile datatype
used in Python. Python has a great built-in list type named "list". List literals
are written within square brackets [ ]. Lists work similarly to strings -- use the
len() function and square brackets [ ] to access data, with the first element at
index 0. The list type is a container that holds a number of other objects, in a
given order. The list type implements the sequence protocol, and also allows
you to add and remove objects from the sequence.
Example

Empty List
>>> list=[ ]
>>> list
[]
Integer List
>>> list1=[1,2,3]
>>> list1
[1, 2, 3]
List with mixed data types
>>> list2=[10,25.5,'prema']
>>> list2
[10, 25.5, 'prema']
Nested List
>>> list4=["selvi",
[10,20,30],'prema']
>>> list4
['selvi', [10, 20, 30], 'prema']

Accessing List elements


User can use the index operator [] to access an item in a list. Index
starts from 0. So, a list having 5 elements will have index from 0 to 4.

Trying to access an element other that this will raise an IndexError.


The index must be an integer. We can’t use float or other types, this will
result into TypeError.

Example

>>> list=[10,20,30,40,50]
>>> print(list[0])
10
>>> print(list[3])
40
>>> list=['a', 'b', 'c', 'd']
>>> list[3]
'd'
>>> list=['Tamil', 'Kavi',
'Duraisamy']
>>> print(list[2])
Duraisamy

>>> list4=["Kavitha",
[10,20,30],'Tamil']

>>> list4[0]

'Kavitha'

>>> list4[0][0]

'K'

>>> list4[1][0]

10

>>> list4[2][0]

'T'

4.1.1. List operators


Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list, not
a string. Python list supports two kind of operators namely concatenation (+),
repetition (*).

i) Concatenation

Concatenation operator is used to join or concatenate elements of two


or more list. Operator used for concatenation is Plus (+) operator.

Example

>>> list1=[10,20,30,40,50]

>>> list2=['a','b','c']

>>> list3=['Tamil', 'kavi','duraisamy']

>>> list1+list2

[10, 20, 30, 40, 50, 'a', 'b', 'c']

>>> list1+list2+list3

[10, 20, 30, 40, 50, 'a', 'b', 'c', 'Tamil', 'kavi', 'duraisamy']

ii. Repetition

Repetition operator is used to repeat the list for given number of times.
Operator used for repetition is asterisk (*) operator.

Example

>>>list1=[10, 20, 30, 40, 50]

>>> list2=['a','b','c']

>>> list3=['Tamil', 'kavi','duraisamy']

>>> list1*2

[10, 20, 30, 40, 50, 10, 20, 30, 40, 50]

>>> list2*3

['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']


4.1.2. List slices

User can access a range of items in a list by using the slicing operator
colon (:). A subsequence of a sequence is called a slice and the operation that
extracts a subsequence is called slicing. Like with indexing, we use square
brackets ([ ]) as the slice operator, but instead of one integer value inside we
have two, separated by a colon (:). Python also allows slicing of the lists. User
can access a part of complete list by using index range.

Syntax

list_name[start:end]

‘start’ indicates starting index of the list to be sliced. ‘End’ indicates


end of the list element to be sliced. Negative index takes values from the
last.

Example

>>> list=[10,20,30,40,50,60,70]

>>> list[0:5]

[10, 20, 30, 40, 50]

>>> list[2:6]

[30, 40, 50, 60]

>>> list[:3]

[10, 20, 30]

>>> list[1:]

[20, 30, 40, 50, 60, 70]

>>> list[:]

[10, 20, 30, 40, 50, 60, 70]

>>> list[:-5]

[10, 20]

>>> list[-2:]

[60, 70]
4.1.3. List Methods

Methods that are available with list object in Python programming are
tabulated below. They are accessed as list.method(). Some of the methods
have already been used above.

Built-in Functions

Method Purpose Example


>>>
Returns the length of the list=[10,20,30,40,50]
len(list)
list >>> len(list)
5
>>>
list=[10,20,30,40,50]
Returns the minimum value >>> min(list)
min(list)
of the list 10
>>> max(list)
50
>>>
Returns the maximum value list=[10,20,30,40,50]
max(list)
of the list >>> max(list)
50

Various list methods are given below

i. append( )

The method list.append(x) will add an item (x) to the end of a list.
Appends object obj to list.

Example

>>> list=[10,20,30]
>>> list.append(40)
>>> list
[10, 20, 30, 40]

ii. insert( )

Insert an item at the specified index. The list.insert(i,x) method takes


two arguments, with i being the index position you would like to add an item to,
and x being the item itself.

Example

>>> list=['a','c','d','e']
>>> list.insert(1,'b')
>>> list
['a', 'b', 'c', 'd', 'e']

iii. count( )

The list.count(x) method will return the number of times the value x
occurs within a specified list. Return the count of number of items passed as
an argument.

Example

>>> list=[1,1,2,3,4,'a','a','b','tamil']
>>> list.count(1)
2
>>> list.count('tamil')
1

iv. extend( )

If user want to combine more than one list, then user can use the
list.extend(L) method, which takes in a second list as its argument. Add all
elements of a list to the another list.

Example

>>> list1=['tamil','kavi']
>>> list2=['duraisamy','sivalingam','amma']
>>> list1.extend(list2)
>>> list1
['tamil', 'kavi', 'duraisamy', 'sivalingam', 'amma']

v. index( )

Method used to return the index of the first matched item in the list.
When lists start to get long, it becomes more difficult for us to count out our
items to determine at what index position a certain value is lo-cated. We can use
list.index(x), where x is equivalent to an item value, to return the index in the list
where that item is located. If there is more than one item with value x, this
method will return the first index location.

Example

>>> list=[1,1,2,4,5,3,1,1,3,5,3]
>>> list.index(1)
0
>>> list.index(3)
5
>>> list.index(7)
ValueError: 7 is not in list
vi. remove( )

Method used to remove an element from the list. When user need to
remove an item from a list, remove(x) method which removes the first item
in a list whose value is equivalent to x can be used.

Example

>>> list=['cse','ece','eee','eie','civil']
>>> list.remove('eie')
>>> list
['cse', 'ece', 'eee', 'civil']

vii. pop( )

Method used to remove and returns an element removed from the list.
User can use the list.pop([i]) method to return the item at the given index
position from the list and then remove that item.

Example

>>> list=['cse','ece','eee','eie','civil']
>>> list.pop(3)
'eie'
>>> list
['cse', 'ece', 'eee', 'civil']

viii. reverse( )

Method used to reverse the order of items in the list. User can reverse
the order of items in a list by using the list.reverse() method. Perhaps it is
more convenient for us to use reverse alphabetical order rather than
traditional alphabetical order.

Example

>>> list=['b','z','a','c','e']
>>> list.reverse()
>>> list
['e', 'c', 'a', 'z', 'b']
>>> list2=[10,20,30,40]
>>> list2.reverse()
>>> list2
[40, 30, 20, 10]
ix. sort( )

Method used to sort items in a list in ascending order. User can use the
list.sort() method to sort the items in a list.

Example

>>> list=['b','z','a','c','e']
>>> list.sort()
>>> list
['a', 'b', 'c', 'e', 'z']
>>> list2=[20,40,10,50,30]
>>> list2.sort()
>>> list2
[10, 20, 30, 40, 50]

x. clear( )

User can remove all values contained in it by using the list.clear()


method. Method used to clear or remove all the elements in the list.

Example

>>> list=[20,40,10,50,30]
>>> list
[20, 40, 10, 50, 30]
>>> list.clear()
>>> list
[]

xi. copy( )

Method used to copy elements of the list. When user working with a
list and may want to manipulate it in multiple ways while still having the
original list available to us unchanged, user can use list.copy() to make a
copy of the list.

Example

>>> list=['tamil','kavi','selva','durai']
>>> new=list.copy()
>>> new
['tamil', 'kavi', 'selva', 'durai']
4.1.4 List Loop

User use a loop to access all the elements in a list. A loop is a block of
code that repeats itself until it runs out of items to work with, or until a
certain condition is met. In this case, our loop will run once for every item in
our list. With a list that is three items long, our loop will run three times.
Using a “for” loop user can iterate though each item in a list. It has the ability
to iterate over the items of any sequence, such as a list or a string.

Syntax

for iterating_var in sequence:

statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the


first item in the sequence is assigned to the iterating variable iterating_var.
Next, the statements block is executed. Each item in the list is assigned
to iterating_var, and the statement(s) block is executed until the entire
sequence is exhausted.

Flowchart

for iterating_var in
sequence:

If no more item in
Item sequence
from Next
sequenc statement
e
True

Body of the loop


Example

>>> for fruit in ['apple','banana','mango']:


... print("I like",fruit)
...
I like apple
I like banana
I like mango

>>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]]


>>> for x in mylist:
... if len(x)==3:
... print x
...
[1, 2, 3]
[8, 9, 10]
colors=['Red','Blue','Green','Yellow','Pink']
for a in colors:
print(a)

Red
Blue
Green
Yellow
Pink

4.1.5 List Mutability

Lists are mutable, which means user can change their elements.
Using the bracket operator on the left side of an assignment, user can update
one of the elements.

Example

>>> list=['red','blue','green','white']
>>> list
['red', 'blue', 'green', 'white']
>>> list[3]='black'
>>> list
['red', 'blue', 'green', 'black']

The bracket operator applied to a list can appear anywhere in an ex-


pression. When it appears on the left side of an assignment, it changes one of
the elements in the list, so the first element of list has been changed from
‘white’ to ‘black’. An assignment to an element of a list is called item
assignment. Item assignment does not work for strings.
Example

>>> str="TEST"
>>> str
'TEST'
>>> str[2]="X"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item
assignment
>>> list1=['T','E','S','T']
>>> list[2]='X'
>>> list1[2]='X'
>>> list1
['T', 'E', 'X', 'T']

With the slice operator we can update several elements at once:

>>> a=['a','b','c','d','e','f']
>>> a
['a', 'b', 'c', 'd', 'e', 'f']
>>> a[1:3]=['z','x']
>>> a
['a', 'z', 'x', 'd', 'e', 'f']

User can also remove elements from a list by assigning the empty list to
them:

>>> a
['a', 'z', 'x', 'd', 'e', 'f']
>>> a[1:3]=[]
>>> a
['a', 'd', 'e', 'f']
Mutable list allows users to delete list element using del keyword

>>> name=['tamil','selva','kavi']
>>>name
['tamil', ‘selva’, 'kavi']
>>> del name[1]
>>> name
['tamil', 'kavi']
4.1.6. List Aliasing

Alias name is used to indicate that a named list is also known or more
familiar under another specified name. Since variables refer to objects, if user
assign one variable to another, both variables refer to the same object.

Example

>>> a=[10,20,30]
>>> b=a
>>> b
[10, 20, 30]
>>> a is b
True

Both names indicate the same list. Changes made to the list with one name
are also reflected in another name. Alias provide two different names given
to one list.

Example

>>> a
[10, 20, 30]
>>> b[1]=25
>>> a
[10, 25, 30]

4.1.7 Cloning List

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.

Syntax

new_list = old_list[:]

The easiest way to clone a list is to use the slice operator:

>>> list=[10,20,30]
>>> new=list[:]
>>> new
[10, 20, 30]
Taking any slice of a creates a new list. In this case the slice happens to
consist of the whole list. Changes made in new list will not reflect in old list
as like in alias. Now we are free to make changes to new without worrying
about old list.

Example

>>> new[2]=25
>>> new
[10, 20, 25]
>>> list
[10, 20, 30]

4.1.8. List Parameters

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 parameter change the argument as well.

some_list = ["some", "values", "in", "a", "list", ]


func(*some_list)

This is equivalent to:

func("some", "values", "in", "a", "list")

The fixed x param might warrant a thought:

func(5, *some_list)
func(5, "some", "values", "in", "a", "list")
4.2. Tuples

A tuple is a sequence of values like a list. The values stored in a tuple


can be any type, and they are indexed by integers. A tuple is a sequence of
immutable Python objects. The important difference between list and tuple is
that tuples are immutable i.e., the values of tuples cannot be changed but
values of list can be updated. Tuples use parentheses “( )”.

Creating a tuple is as simple as putting different comma-separated


values. Optionally you can put these comma-separated values between
parentheses also. Python has a very powerful tuple assignment feature that
allows a tuple of variables on the left of an assignment to be assigned values
from a tuple on the right of the assignment.

Example

>>> tup=(10,20,30)
>>> print(tup)
(10, 20, 30)
>>> tup2=('a','b','c')
>>> tup2
('a', 'b', 'c')
>>> tup3=("tamil","selvan","kavi")
>>> tup3
('tamil', 'selvan', 'kavi')
>>> tup4=(10,20.5,'a',"tamil")
>>> tup4
(10, 20.5, 'a', 'tamil')

4.2.1. Tuples are immutable

Values of tuples cannot be changed or updated. List are mutable, that


is values of list can be changed or updated. Hence tuples are immutable. If
user try to modify, it will generate an error message.

Example
>>>tup=(10,20,30,40,50)
>>>tup
(10,20,30,40,50)
>>> tup[1]=15
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item
assignment

4.2.2 Tuple Assignment

Python has a very powerful tuple assignment feature that allows


a tuple of variables on the left of an assignment to be assigned values from
a tuple on the right of the assignment.

Example
>>> x,y=10,20
>>> print(x,y)
10 20
>>> x,y,z=10,20
ValueError: not enough values to unpack
(expected 3, got 2)
>>> x,y=10,20,30
ValueError: too many values to unpack
(expected 2)

Tuple assignment is often useful to swap the values of two variables.

Example
>>> x=10;y=20
>>> print(x,y)
10 20
>>> temp=x
>>> x=y
>>> y=temp
>>> print(x,y)
20 10

Tuple assignment is more elegant to swap two values.

Example
>>> x,y=10,20
>>> print(x,y)
10 20
>>> x,y=y,x
>>> print(x,y)
20 10
4.2.3. Basic Tuples Operations

i. Concatenation

Two or more tuples can be concatenated or joined using concatenation


operator (+).

Example
>>> t1=(10,20.5,30)
>>> t2=('a','b','c')
>>> t3=('tamil','kavi')
>>> t1+t2+t3
(10, 20.5, 30, 'a', 'b', 'c', 'tamil', 'kavi')

ii. Repetition

Values of tuples can be repeated for specified number of times. User


can repeat the object of the tuple using * operator.

Example
>>> t1=(10,20.5,'a','b','tamil')
>>> t1 * 2
(10, 20.5, 'a', 'b', 'tamil', 10, 20.5, 'a', 'b', 'tamil')
>>> t2=(1,2,3)
>>> t2 * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

iii. Membership

The membership operator in returns True, if the element is in the tuple


else it returns False. Membership operator is used to check whether given
element is in the tuple or not.

Example

>>> t1=(10,20,30,40,50)
>>> print(10 in t1)
True
>>> print(6 in t1)
False
iv. Tuple Indexing

User can use the index operator [] to access an item in a tuple where
the index starts from 0. So, a tuple having 6 elements will have index from 0
to 5. Trying to access an element other that (6, 7,...) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will
result into TypeError.

Example

>>> tuple=('t','a','m','i','l')
>>> print(tuple[0])
t
>>> print(tuple[3])
I

Python tuples allows negative indexing for its sequence. The index of -1
refers to the last item, -2 to the second last item and so on.

Example

>>> tuple=('t','a','m','i','l')
>>> print(tuple[-1])
l
>>> print(tuple[-3])
M

v. Tuple Slicing
User can access a range of items in a tuple by using the slicing
operator. Slicing operator in python language is colon(:).

Example

>>> tuple=('t','a','m','i','l')
>>> print(tuple[0:3])
('t', 'a', 'm')
>>> print(tuple[2:3])
('m',)
>>> print(tuple[2:])
('m', 'i', 'l')
>>> print(tuple[:])
('t', 'a', 'm', 'i', 'l')
>>> print(tuple[:-2])
('t', 'a', 'm')
vi. Deleting a Tuple

User cannot change the elements in a tuple. Likewise user cannot


delete or remove items from a tuple. But deleting a tuple entirely is possible
using the keyword del.

Example

>>> t=(10,20,30)
>>> print(t)
(10, 20, 30)
>>> del t
>>> print(t)
NameError: name 't' is not defined

vii. Comparing Tuples

The comparison 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 element, and so on, until it finds elements that
differ.

Example

>>> t1=(10,20,30)
>>> t2=(5,15,25)
>>> t1>t2
True
>>> t1<t2
False

4.2.4 Tuple built-in function

Built-in functions commonly used with tuples to perform different task


is given below.

Function Description

Return True if all elements of the tuple are true (or if


all()
the tuple is empty).

Return True if any element of the tuple is true. If the


any()
tuple is empty, return False.
enumerate Return an enumerate object. It contains the index and
() value of all the items of tuple as pairs.

len() Return the length (the number of items) in the tuple.

max() Return the largest item in the tuple.

min() Return the smallest item in the tuple

Take elements in the tuple and return a new sorted list


sorted()
(does not sort the tuple itself).

sum() Retrun the sum of all elements in the tuple.

Convert an iterable (list, string, set, dictionary) to a


tuple()
tuple.

count(x) Return the number of items that is equal to x

index(x) Return index of first item that is equal to x

4.2.5. Tuple as return value

Functions can return tuples as return values. This is very useful — we


often want to know some batsman’s highest and lowest score, or we want to
find the mean and the standard deviation, or we want to know the year, the
month, and the day. In each case, a function (which can only return a single
value), can create a single tuple holding multiple elements.

Functions can always only return a single value, but by making that value
a tuple, we can effectively group together as many values as we like, and
return them together. In such case user create a single tuple which holds
multiple elements.
Example

def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)

print(circleInfo(10))
Output
G:\PYTHON\PROGRAM>python tupreturn.py
(62.8318, 314.159)

4.2.6. Difference between Tuple and list

TUPLE LIST
Tuple is collection of different List is collection of different
data type values data type values
Tuple defined using parenthesis List defined using square
“( )” brackets “[ ]”
Tuples are immutable Lists are mutable
Values of tuple cannot be Values of list can be
changed or updated changed or updated
>>> list=[10,20,30]
>>> tup=(10,20,30) >>> print(list)
>>> print(tup) [10, 20, 30]
(10, 20, 30) >>> list[1]=40
>>> tup[1]=40 >>> print(list)
TypeError: 'tuple' object does [10, 40, 30]
not support item assignment

4.3 Dictionaries

A dictionary is an associative array (also known as hashes). Any key


of the dictionary is associated (or mapped) to a value. The values of
a dictionary can be any Python data type. So dictionaries are unordered
key-value-pairs.

Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces. An
empty dictionary without any items is written with just two curly braces, like
this: { }.

Keys are unique within a dictionary while values may not be. The
values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.

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. Dictionaries are optimized to retrieve values when the key is
known.
4.3.1. Dictionary Operation

a. Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square


brackets along with the key to obtain its value.

Example 1

dict = {'Name': 'Tamil', 'Age': 31, 'Class':


'First'}

print "dict['Name']: ", dict['Name']


print "dict['Age']: ", dict['Age']
Output

dict['Name']: Tamil
dict['Age']: 31

If user attempt to access a data item with a key, which is not part of
the dictionary

Example 2

dict = {'Name': 'Tamil', 'Age': 31, 'Class':


'First'}

print "dict['Plcae']: ", dict['Place']


Output

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
KeyError: 'Place'

b. Updating Dictionary

User can update a dictionary by adding a new entry or a key-value pair,


modifying an existing entry, or deleting an existing entry.

Example

>>> print(dict)
{'Name': 'Tamil', 'Age': 31, 'Class': 'First'}
>>> dict['Name']='Tamil Selvan' #Update existing value
>>> print(dict)
{'Name': 'Tamil Selvan', 'Age': 31, 'Class': 'First'}
>>> dict['Place']='Kavindapadi' #Add new entry into dictionary
>>> print(dict)
{'Name': 'Tamil Selvan', 'Age': 31, 'Class': 'First', 'Place':
'Kavindapadi'}
c. Delete Dictionary Elements

User can either remove individual dictionary elements or clear the


entire contents of a dictionary. You can also delete entire dictionary in a
single operation. To explicitly remove an entire dictionary, just use
the del statement.

Example

>>> d1={'Name':'Tamil','Age':31,'Class':'First'}
>>> print(d1)
{'Name': 'Tamil', 'Age': 31, 'Class': 'First'}
>>> del d1['Class']
>>> print(d1)
{'Name': 'Tamil', 'Age': 31}
>>> d1.clear()
>>> print(d1)
{}
>>> del d1
>>> print(d1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd1' is not defined

4.3.2 Properties of Dictionary Keys

Dictionary values have no restrictions. They can be any arbitrary


Python object, either standard objects or user-defined objects. However,
same is not true for the keys.

There are two important points to remember about dictionary keys

(a) More than one entry per key not allowed. Which means no duplicate key
is allowed. When duplicate keys encountered during assignment, the last
assignment wins.

Example

>>> d1={'Name':'Tamil','Age':31,'Class':'First'}
>>> d1['Name']='Selva'
>>> d1
{'Name': 'Selva', 'Age': 31, 'Class': 'First'}

(b) Keys must be immutable. Which means you can use strings, numbers or
tuples as dictionary keys but something like ['key'] is not allowed.
4.3.3. Dictionary Methods

Methods that are available with dictionary are tabulated below. Some
of them have already been used in the above examples.

Method Description Example

d1={'Name':'Tamil','Age':31}
Remove all items form >>> d1.clear()
clear()
the dictionary. >>> d1
{}
>>> d1
{'Name': 'Tamil', 'Age': 31}
Return a shallow copy
copy()
of the dictionary. >>> d1.copy()
{'Name': 'Tamil', 'Age': 31}

Return a new dictionary >>> sequence=('name','age')


fromkeys(seq[, v with keys from seq and >>>
]) value equal to v dict.fromkeys(sequence,10)
(defaults to None). {'name': 10, 'age': 10}
>>>
Return the value of key. d1={'Name':'Tamil','Age':31}
If key doesnot exit, >>> d1.get('Name')
get(key[,d])
return d (defaults 'Tamil'
to None). >>> d1.get('Place')
None
>>>
Return a new view of d1={'Name':'Tamil','Age':31}
items() the dictionary's items >>> d1.items()
(key, value). dict_items([('Name',
'Tamil'), ('Age', 31)])

Return a new view of >>> d1.keys()


keys()
the dictionary's keys. dict_keys(['Name', 'Age'])

Remove the item >>> d1.pop('Age')


with key and return its 31
value or d if key is not >>> print(d1)
pop(key[,d])
found. If d is not {'Name': 'Tamil'}
provided and key is not >>> d1.pop('Place')
found, raises KeyError. KeyError: 'Place'
>>>
Remove and return an
d1={'Name':'Tamil','Age':31}
arbitary item (key,
>>> d1.popitem()
popitem() value).
('Age', 31)
Raises KeyError if the
>>> print(d1)
dictionary is empty.
{'Name': 'Tamil'}
setdefault(key[,d If key is in the >>>
]) dictionary, return its d1={'Name':'Tamil','Age':31}
value.
>>> d1.setdefault('Name')
If not, insert key with a
'Tamil'
value of d and
>>> d1.setdefault('Place')
return d (defaults
None
to None).
>>>
d1={'Name':'Tamil','Age':31}
Update the dictionary
>>> d2={'Place':'KVP'}
with the key/value pairs
update([other]) >>> d1.update(d2)
from other, overwriting
>>> print(d1)
existing keys.
{'Name': 'Tamil', 'Age': 31,
'Place': 'KVP'}

>>> d1.values()
Return a new view of
values() dict_values(['Tamil', 31,
the dictionary's values
'KVP'])

4.3.4. Built-in Dictionary Functions

Python includes the following dictionary functions −

S.No Function with Description

cmp(dict1, dict2)
1
Compares elements of both dict.

len(dict)
2 Gives the total length of the dictionary. This would be
equal to the number of items in the dictionary.

str(dict)
3 Produces a printable string representation of a
dictionary

type(variable)
Returns the type of the passed variable. If passed
4
variable is dictionary, then it would return a dictionary
type.
4.3.5. Advanced List Processing – List Comprehension

Dictionary comprehension is an elegant and concise way to create new


dictionary from an iterable in Python. Dictionary comprehension consists of
an expression pair (key: value) followed by “for” statement inside curly
braces { }. Here is an example to make a dictionary with each item being a
pair of a number and its square.

squares = {x: x*x for x in range(6)}

print(squares)

Output

G:\PYTHON\PROGRAM>python sam.py

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This code is equivalent to

squares = {}

for x in range(6):

squares[x] = x*x

A dictionary comprehension can optionally contain more for or if


statements. An optional if statement can filter out items to form the new
dictionary. Here are some examples to make dictionary with only odd items.

odd_squares = {x: x*x for x in range(11) if x%2 ==


1}

print(odd_squares)

Output

G:\PYTHON\PROGRAM>python sam.py

{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}


4.3.6. Other Dictionary Operations

a. Dictionary Membership Test

User can test if a key is in a dictionary or not using the keyword in.
Notice that membership test is for keys only, not for values.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

print(1 in squares) # Output: True

print(2 not in squares) # Output: True

# membership tests for key only not value

print(49 in squares) # Output: False

Output

True
True
False

b. Iterating Through a Dictionary

Using a for loop we can iterate though each key in a dictionary.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

for i in squares:

print(squares[i])

Output

G:\PYTHON\PROGRAM>python sam.py
1
9
25
49
81
4.4. Illustrative Programs

4.4.1 Selection Sort

Selection sorting is conceptually the simplest sorting algorithm. This


algorithm finds the smallest element in an array and exchanges it with the
element in the first position, then finds the second smallest element and
exchange it with the element in the second position, and continues in this
way until the entire array is sorted.

Principle of Selection sort

If the array contains ‘n’ elements in an array,

i. First Element

 First element is compared with remaining (n-1) elements


 Find the smallest element.
 It is swapped with first element

ii. Second Element

 First element is compared with remaining (n-2) elements


 Find the smallest element.
 It is swapped with second element

iii. So on

Example

Sort the following elements using Selection sort. 23, 78, 45, 8, 32, 56

1. Initial List

23 78 45 8 32 56

swap

2. Pass 1

8 78 45 23 32 56

swap
3. Pass 2

8 23 45 78 32 56

swap
4. Pass 3

8 23 32 78 45 56

swap
5. Pass 4

8 23 32 45 78 56

swap
6. Pass 5

8 23 32 45 56 78

Sorted List

Sorting using Selection Sort Algorithm

void selectionSort(int a[], int size)


{
int i, j, min, temp;
for(i=0; i < size-1; i++ )
{
min = i; //setting min as i
for(j=i+1; j < size; j++)
{
if(a[j] < a[min])
{
min = j; //then set min as j
}
}
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}

Python Program
# Python program for implementation of Selection Sort
import sys
A = [64, 25, 12, 22, 11]

# Traverse through all array elements


for i in range(len(A)):

# Find the minimum element in remaining unsorted array


min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with


# the first element
temp=A[i]
A[i]=A[min_idx]
A[min_idx]=temp

# Driver code to test above


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i])

Output

G:\PYTHON\PROGRAM>python selection.py
Sorted array
11
12
22
25
64
4.4.2. Insertion Sort

It is a simple Sorting algorithm which sorts the array by shifting


elements one by one. There are two zone considered in the insertion sort.
Each successive element in the array to be sorted is taken from list one-by-
one. Insert them in their appropriate place of the sorted zone

Example

Sort the following elements using Insertion sort. 30, 70, 20, 40, 10, 60

Sorted Zone Unsorted Zone

30 70 20 40 10 60

30
70 20 40 10 60

30 70 20 40 10 60

20 30 70
40 10 60

20 30 40 70
10 60

10 20 30 40 70
60

10 20 30 40 60 70

Sorting using Insertion Sort Algorithm

int a[6] = {30,70,20,40,10,60};


int i, j, key;
for(i=1; i<6; i++)
{
key = a[i];
j = i-1;
while(j>=0 && key < a[j])
{
a[j+1] = a[j];
j--;
}
a[j+1] = key;
}
Python Program

# Python program for implementation of Insertion Sort

# Function to do insertion sort


def insertionSort(arr):

# Traverse through 1 to len(arr)


for i in range(1, len(arr)):

key = arr[i]

# Move elements of arr[0..i-1], that are


# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

# Driver code to test above


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])

Output

Sorted array is:


5
6
11
12
13
4.4.3. Merge Sort

Merge sort is a sorting algorithm that uses divide and Conquer strategy. It is
an external sorting algorithm. Merge Sort is quite fast, and has a time
complexity of O(n log n). It is a stable sort, which means the "equal"
elements are ordered in the same order in the sorted list.

Merge sort contains 3 steps,

 Divide  Partition the given array into 2 sublists (s1 and s2).
 Conquer  Sort s1 and s2 separately.
 Combine  Finally combine sorted list together.

Example

Sort the following data using Merge Sort 70, 20, 30, 40, 10, 50, 60

70 20 30 40 10 50 60

70 20 30 40 10 50 60

70 20 30 40 10 50 60

70 20 30 40 10 50 60

20 70 30 10 40 50 60

20 30 70 10 40 50 60

10 20 30 40 50 60 70
Sorting using Merge Sort Algorithm

MergeSort(int A[ ], int low, int high)


{
if(low < high)
{
mid  (low + high) / 2;
MergeSort(A, low, mid);
MergeSort(A, mid+1, high);
Combine(A, low, mid, high);
}
}
Combine(int A[ ], int low, int mid, int high)
{
klow;
ilow;
j mid+1;
while( i ≤ mid && j ≤ high)
{
if(A[i] ≤ A[j])
{
temp[k] A[i];
i = i + 1;
k = k+1;
}
else
{
temp[k] A[j];
j = j + 1;
k = k+1;
}
}
while( i ≤ mid)
{
temp[k] A[i];
i = i + 1;
k = k+1;
}
while( j ≤ high)
{
temp[k] A[j];
j = j + 1;
k = k+1;
}
}
Python Program

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 lefthalf[i] < 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)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
Output

G:\PYTHON\PROGRAM>python mer.py

Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
Splitting [54, 26]
Splitting [54]
Merging [54]
Splitting [26]
Merging [26]
Merging [26, 54]
Splitting [93, 17]
Splitting [93]
Merging [93]
Splitting [17]
Merging [17]
Merging [17, 93]
Merging [17, 26, 54, 93]
Splitting [77, 31, 44, 55, 20]
Splitting [77, 31]
Splitting [77]
Merging [77]
Splitting [31]
Merging [31]
Merging [31, 77]
Splitting [44, 55, 20]
Splitting [44]
Merging [44]
Splitting [55, 20]
Splitting [55]
Merging [55]
Splitting [20]
Merging [20]
Merging [20, 55]
Merging [20, 44, 55]
Merging [20, 31, 44, 55, 77]
Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]
4.4.4. Python program 1 for Histogram

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

G:\PYTHON\PROGRAM>python hist.py
**
***
******
*****

4.4.5. Python program 2 for Histogram

import plotly.plotly as py

import plotly.graph_objs as go

import numpy as np

x = np.random.randn(500)

data = [go.Histogram(x=x)]

py.iplot(data, filename=’basic histogram’)

Output
4.4.6. Students marks statement

sub1=int(input("Enter marks of the first subject: "))


sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")

OUTPUT:
Case 1:
Enter marks of the first subject: 85
Enter marks of the second subject: 95
Enter marks of the third subject: 99
Enter marks of the fourth subject: 93
Enter marks of the fifth subject: 100
Grade: A

Case 2:
Enter marks of the first subject: 81
Enter marks of the second subject: 72
Enter marks of the third subject: 94
Enter marks of the fourth subject: 85
Enter marks of the fifth subject: 80
Grade: B
4.4.7. Retail bill preparation

Python code to check the Grocery List


# This loop will go on until the budget is integer or float
while True:
try:
bg = float(input("Enter your budget : "))
# if budget is integer or float it will be stored
# temporarily in variable 's'
s = bg
except ValueError:
print("PRINT NUMBER AS A AMOUNT")
continue
else:
break

# dictionary to store product("name"),


quantity("quant"),
# price("price") with empty list as their values
a ={"name":[], "quant":[], "price":[]}

# converting dictionary to list for further updation


b = list(a.values())

# variable na value of "name" from dictionary 'a'


na = b[0]

# variable qu value of "quant" from dictionary 'a'


qu = b[1]

# variable pr value of "price" from dictionary 'a'


pr = b[2]

# This loop terminates when user select 2.EXIT option


when asked
# in try it will ask user for an option as an integer (1 or
2)
# if correct then proceed else continue asking options
while True:
try:
ch = int(input("1.ADD\n2.EXIT\nEnter your choice : "))
except ValueError:
print("\nERROR: Choose only digits from the given
option")
continue
else:
# check the budget is greater than zero and option
selected
# by user is 1 i.e. to add an item
if ch == 1 and s>0:

# input products name


pn = input("Enter product name : ")
# input quantity of product
q = input("Enter quantity : ")
# input price of the product
p = float(input("Enter price of the product : "))
if p>s:
# checks if price is less than budget
print("\nCAN, T BUT THE PRODUCT")
continue
else:
# checks if product name already in list
if pn in na:
# find the index of that product
ind = na.index(pn)
# remove quantity from "quant" index of the
product
qu.remove(qu[ind])
# remove price from "price" index of the product
pr.remove(pr[ind])

# insert new value given by user earlier


qu.insert(ind, q)

# insert new value given by user


earlier
pr.insert(ind, p)

# subtracting the price from the budget and assign


# it to 's' sum(pr) is because pr = [100, 200] if
# budget is 500 then s = bg-sum(pr) = 200
# after updating for same product at index 0 let
# pr = [200, 200] so s = 100
s = bg-sum(pr)

print("\namount left", s)
else:
# append value of in "name", "quantity", "price"
na.append(pn)

# as na = b[0] it will append all the value in the


# list eg: "name":["rice"]
qu.append(q)

# same for quantity and price


pr.append(p)
# after appending new value the sum in price
# as to be calculated
s = bg-sum(pr)
print("\namount left", s)
# if budget goes zero print "NO BUDGET"
elif s<= 0:
print("\nNO BUDGET")
else:
break

# will print amount left in variable 's'


print("\nAmount left : Rs.", s)

# if the amount left equals to any amount in price list


if s in pr:
# then printing the name of the product which can
buy
print("\nAmount left can buy you a", na[pr.index(s)])
print("\n\n\nGROCERY LIST")

# print final grocery list


for i in range(len(na)):
print(na[i], qu[i], pr[i])

OUTPUT
Enter Your budget : 500
1.Add an item
2.Exit
Enter your choice : 1

Enter product : corn flour


Enter quantity : 1.5 kg
Enter Price : 100

Amount left : 400

1.Add an item
2.Exit
Enter your choice : 1

Enter product : wheat


Enter quantity : 2 kg
Enter Price : 100

Amount left : 300

1.Add an item
2.Exit
Enter your choice : 1

Enter product : corn flour


Enter quantity : 2 kg
Enter Price : 250

Amount left : 150

1.Add an item
2.Exit
Enter your choice : 1

Enter product : rice


Enter quantity : 5 kg
Enter Price : 300

Can't Buy the product ###(because budget left is 150)

1.Add an item
2.Exit
Enter your choice : 1

Enter product : xyz


Enter quantity : 1 kg
Enter Price : 50

Amount left : 100

1.Add an item
2.Exit
Enter your choice : 2

Amount left can buy you wheat

GROCERY LIST is:


Product name Quantity Price
corn flour 2 kg 250
wheat 2 kg 100
xyz 1 kg 50

You might also like