0% found this document useful (0 votes)
30 views15 pages

Python Module 2 Notes

4

Uploaded by

Aditya Vernekar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
30 views15 pages

Python Module 2 Notes

4

Uploaded by

Aditya Vernekar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Introduction to Python Programming

Module 2: Lists, Dictionaries and Structuring Data

1. What is a List? Explain append( ), insert( ) and remove( ) methods with examples
June/July 2023 (8M)
A list is a value that contains multiple values in an ordered sequence.
A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
A list begins with an opening square bracket and ends with a closing square bracket,
[ ].Values inside the list are also called items and are separated with commas

append( ) and insert( ) methods

 To add new values to a list, use the append( ) and insert( ) methods.
 The append( ) method call adds the argument to the end of the list.
Example:

 The insert( ) method can insert a value at any index in the list. The first argument to insert( ) is the
index for the new value, and the second argument is the new value to be inserted.

Example:

remove ( ) methods

 The remove( ) method is passed the value to be removed from the list it is called on.
Example:

 If the value appears multiple times in the list, only the first instance of the value will be removed.

 The remove( ) method is good when you know the value you want to remove from the list.

Prof. Jillian Rufus J, Dr. TTIT Page 1


Introduction to Python Programming

2. Explain the following methods with example:


i)keys( ) ii) values( ) iii) items( ) June/July 2023 (12M )

The keys(), values(), and items() Methods


 There are three dictionary methods that will return list-like values of the dictionary’s keys, values,
or both keys and values: keys(), values(), and items().
 Data types (dict_keys, dict_values, and dict_items, respectively) can be used in for loops.

Example:

 A for loop can iterate over the keys, values, or key-value pairs in a dictionary by using keys(),
values(), and items() methods.
 The values in the dict_items value returned by the items() method are tuples of the key and value.

Example:

 If we want a true list from one of these methods, pass its list-like return value to the list() function.
Example:

 The list(spam.keys()) line takes the dict_keys value returned from keys() and passes it to list(),
which then returns a list value of ['color', 'age'].
 We can also use the multiple assignment trick in a for loop to assign the key and value to separate
variables.

Prof. Jillian Rufus J, Dr. TTIT Page 2


Introduction to Python Programming

Example:

3. How is tuple different from a list and which function is used to convert list to tuple? Explain
June/July 2023 (6M )

 The tuple data type is almost identical to the list data type, except in two ways.
 First, tuples are typed with parentheses, ( and ), instead of square brackets, [ and ].

Example:

 Second, benefit of using tuples instead of lists is that, because they are immutable and their contents
don’t change. Tuples cannot have their values modified, appended, or removed.
Example:

 If you have only one value in your tuple, you can indicate this by placing a trailing comma after the
value inside the parentheses.

Converting Types with the list() and tuple() Functions

 The functions list() and tuple() will return list and tuple versions of the values passed to them.

Prof. Jillian Rufus J, Dr. TTIT Page 3


Introduction to Python Programming

 Converting a tuple to a list is handy if you need a mutable version of a tuple value.

4. List the merits of dictionary over list. June/July 2023 (4M )

1. The dictionary is created by placing elements in { } as “key”:”value”, each key-value pair is


separated by commas “, “
2. Unlike lists, items in dictionaries are unordered.
3. We can have arbitrary values for the keys that allows us to organize our data in powerful ways.
4. The list is an ordered collection of data, whereas the dictionaries store the data in the form of key-
value pairs using the hashtable structure.
5. Dictionary is used to store large amounts of data for easy and quick access
6. Dictionaries are used to build the indexes of the content
7. Dictionaries are used when you wish to build the map objects

5. Read N numbers from the console and create a list. Develop a program to compute and print
mean, variance and standard deviation with messages June/July 2023 (10M )

Program:

N=int(input(‘Enter the number of elements:’))

lis=[ ]
For i in range(N):
lis.append(int(input(‘Enter the element:’)))

mean = round(sum(lis)/N,2)
print(‘\nMean is ‘,mean)

lis_mean=[ ]
for i in range(N):
lis_mean.append((lis[i]-mean)**2)

variance = round(sum(lis_mean)/N,2)
print(‘Variance is’,variance)

SD = round(variance**(1/2),2)
print(‘Standard deviation is’,SD)
if SD>=1.5:
print(‘High Dispersion, Low reliability.’)
else:
print(‘Low Dispersion, Reliable.’)
Prof. Jillian Rufus J, Dr. TTIT Page 4
Introduction to Python Programming

Output:
Enter the number of elements: 8
Enter the element: 10
Enter the element: 12
Enter the element: 23
Enter the element: 23
Enter the element: 16
Enter the element: 23
Enter the element: 21
Enter the element: 16

Mean is 18.0
Variance is 24.0
Standard deviation is 4.9
High Dispersion, Low Reliability.

6. Explain with a programming example to each


i) get( ) ii) setdefault( ) 6M

The get( ) Method


Dictionaries have a get() method that takes two arguments:
 The key of the value to retrieve and
 A fallback value to return if that key does not exist.

The setdefault() Method


 To set a value in a dictionary for a certain key only if that key does not already have a value.

 The setdefault() method offers a way to do this in one line of code.


 Setdeafault() takes 2 arguments:
o The The first argument is the key to check for, and
o second argument is the value to set at that key if the key does not exist. If the key does exist,the
setdefault() method returns the key’s value.

Prof. Jillian Rufus J, Dr. TTIT Page 5


Introduction to Python Programming

 The first time setdefault() is called, the dictionary in spam changes to {'color': 'black', 'age': 5, 'name':
'Pooka'}. The method returns the value 'black' because this is now the value set for the key 'color'. When
spam.setdefault('color', 'white') is called next, the value for that key is not changed to 'white' because
spam already has a key named 'color'.


7. Discuss list and dictionary data structure with example for each. 6M
List
A list is a value that contains multiple values in an ordered sequence.
A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
A list begins with an opening square bracket and ends with a closing square bracket,
[ ].Values inside the list are also called items and are separated with commas

Example:

Dictionary

A dictionary is a collection of many values. Indexes for dictionaries can use many different data types,
not just integers. Indexes for dictionaries are called keys, and a key with its associated value is called a
key-value pair. A dictionary is typed with braces, {}.

Example:

Prof. Jillian Rufus J, Dr. TTIT Page 6


Introduction to Python Programming

This assigns a dictionary to the myCat variable. This dictionary’s keys are 'size', 'color', and
'disposition'. The values for these keys are 'fat', 'gray', and 'loud', respectively. You can access these
values through their keys:

8. Read a multi-digit number from the console. Develop a program to print the frequency of each
digit with suitable message.

Program:

import pprint

message = input (‘Enter your input:’)

count={}

for character in message:

count.setdefault(character,0)

count[character] = count[character] +1

print(‘Frequency of words appeared in the sentence or paragraph\n’)

pprint.pprint(count)

print( )

for k, v in count.items( ):

print(‘Character \”+str(k)+’\’ appeared’ + str(v)+ ‘times’)

Output:

Enter your input:

123456123456

{‘1’: 2

‘2’ : 2

‘3’ : 2

‘4’ : 2

Prof. Jillian Rufus J, Dr. TTIT Page 7


Introduction to Python Programming

‘5’ : 2

‘6’ : 2}

Character ‘1’ appeared 2 times

Character ‘2’ appeared 2 times

Character ‘3’ appeared 2 times

Character ‘4’ appeared 2 times

Character ‘5’ appeared 2 times

Character ‘6’ appeared 2 times

Prof. Jillian Rufus J, Dr. TTIT Page 8


Introduction to Python Programming

Prof. Jillian Rufus J, Dr. TTIT Page 9


Introduction to Python Programming

Prof. Jillian Rufus J, Dr. TTIT Page 10


Introduction to Python Programming

Prof. Jillian Rufus J, Dr. TTIT Page 11


Introduction to Python Programming

Prof. Jillian Rufus J, Dr. TTIT Page 12


Introduction to Python Programming

Prof. Jillian Rufus J, Dr. TTIT Page 13


Introduction to Python Programming

Prof. Jillian Rufus J, Dr. TTIT Page 14


Introduction to Python Programming

Prof. Jillian Rufus J Page 15

You might also like