0% found this document useful (0 votes)
15 views5 pages

Module 2 Important Questions With Answer

The document discusses list and dictionary data structures in Python, highlighting their definitions, differences, and various methods for manipulation. Lists are ordered collections enclosed in square brackets, while dictionaries are unordered collections of key-value pairs enclosed in curly braces. It also covers operations such as deletion, indexing, and the use of built-in functions like len(), sum(), max(), and min(), along with programming examples.

Uploaded by

WOLFIE
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)
15 views5 pages

Module 2 Important Questions With Answer

The document discusses list and dictionary data structures in Python, highlighting their definitions, differences, and various methods for manipulation. Lists are ordered collections enclosed in square brackets, while dictionaries are unordered collections of key-value pairs enclosed in curly braces. It also covers operations such as deletion, indexing, and the use of built-in functions like len(), sum(), max(), and min(), along with programming examples.

Uploaded by

WOLFIE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Module-2 1. Discuss list and dictionary data structure with example for each.

Lists, Dictionaries and Structuring Data List: A list is an ordered data structure with elements separated by a comma and
enclosed within square brackets. A list is a value that contains multiple values in
1. Discuss list and dictionary data structure with example for each. an ordered sequence.

2. What is list and dictionary? What are the differences between List & Dictionary? A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
Just as string values are typed with quote characters to mark where the string
3. Explain the methods that are used to delete items from the list
begins and ends, a list begins with an opening square bracket and ends with a
closing square bracket, []. Values inside the list are also called items. Items are
4. Explain negative indexing, slicing, index(),append(),remove(),pop(),insert() & sort().
separated with commas.
5. Explain with a programming example to each: Examples: [1, 2, 3], ['hello', 3.1415, True, None, 42],
(ii) get () spam = ['cat', 'bat', 'rat', 'elephant']
(iii)setdefault()
Dictionary: Dictionary is a collection of many values. The dictionary is an
6. Explain the following methods in list with an examples: unordered collection that contains key: value pairs separated by commas inside
(i)len() (ii)sum() (iii)max() (iv)min() curly brackets
myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
This dictionary’s keys are 'size', 'color', and 'disposition'. The values for these
7. Develop suitable Python programs with nested lists to explain copy.copy( ) and keys are 'fat', 'gray', and 'loud', respectively.
copy.deepcopy( ) methods.
Dictionaries can still use integer values as keys, just like lists use integers for
8. Explain the use of in operator and not in operators in list with suitable examples.
indexes, but they do not have to start at 0 and can be any number.
spam = {12345: 'Luggage Combination', 42: 'The Answer'}

Programs 2. What are the differences between List & Dictionary?


1. Read a multi-digit number (as chars) from the console. Develop a program to print the List Dictionary
frequency of each digit with suitable message. A list is an ordered data structure Items in dictionaries are unordered
List is a mutable Dictionary is a mutable
2. Develop a program to find mean, variance and standard deviation. Lists are denoted by [ ] square Dictionary is denoted by { }
brackets Curly braces
3. Write a python program to accept n numbers and store them in a list. Then print the list Ex: ['cat', 'bat', 'rat', 'elephant'], myCat = {'size': 'fat', 'color': 'gray',
without ODD numbers in it. [1,2,3] 'disposition': 'loud'}
4. Develop a python program to swap cases of a given string.
Slicing can be done Slicing cannot be done
Input: Java Lists can contain duplicate Cannot contain duplicate keys, but
Output: jAVA
elements can contain du[plicate values
>>> spam = ['cats', 'dogs', 'moose'] >>> spam[-3]
>>> bacon = ['dogs', 'moose', 'cats'] 'bat'
>>> spam == bacon Slicing: A slice can get several values from a list, in the form of a new list. A
False slice is typed between square brackets, like an index, but it has two integers
>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'} separated by a colon.
>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'} In a slice, the first integer is the index where the slice starts. The second integer
>>> eggs == ham is the index where the slice ends. A slice goes up to, but will not include, the
True value at the second index. A slice evaluates to a new list value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
3. Explain the methods that are used to delete items from the list. >>> spam[0:4]
Removing Values from Lists with del Statements ['cat', 'bat', 'rat', 'elephant']
The del statement will delete values at an index in a list. All of the values in >>> spam[1:3]
the list after the deleted value will be moved up one index. For example ['bat', 'rat']
>>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[0:-1]
>>> del spam[2] ['cat', 'bat', 'rat']
>>> spam
index(): In a list ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam.
['cat', 'bat', 'elephant']
The Python code spam[0] would evaluate to 'cat', and spam[1] would evaluate
>>> del spam[2]
to 'bat', and so on. The integer inside the square brackets that follows the list
>>> spam
is called an index. The first value in the list is at index 0, the second value is
['cat', 'bat']
at index 1, and the third value is at index 2, and so on.
Removing Values from Lists with remove() >>> spam = ['cat', 'bat', 'rat', 'elephant']
The remove() method is passed the value to be removed from the list it is >>> spam[0]
called on. 'cat'
>>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[1]
>>> spam.remove('bat') 'bat'
>>> spam[2]
>>> spam
'rat'
['cat', 'rat', 'elephant']
>>> spam[3]
'elephant
4. Explain negative indexing, slicing, index(),append(),remove(),pop(),insert() & sort().
Negative Indexing: While indexes start at 0 and go up, you can also use remove():The remove() method is passed the value to be removed from the
negative integers for the index. The integer value -1 refers to the last index in list it is called on.
a list, the value -2 refers to the second-to-last index in a list, and so on. >>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam.remove('bat')
>>> spam[-1] >>> spam
'elephant' ['cat', 'rat', 'elephant']
>>> picnicItems = {'apples': 5, 'cups': 2}
pop():Removes the element at the specified position. >>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
fruits = ['apple', 'banana', 'cherry'] >>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
fruits.pop(1) 'I am bringing 0 eggs
print(fruits)
['apple', 'cherry'] The setdefault() Method
You’ll often have to set a value in a dictionary for a certain key only if that
insert():The insert() method can insert a value at any index in the list. The key does not already have a value. The code looks something like this:
first argument to insert() is the index for the new value, and the second
argument is the new value to be inserted. spam = {'name': 'Pooka', 'age': 5}
>>> spam = ['cat', 'dog', 'bat'] if 'color' not in spam:
>>> spam.insert(1, 'chicken') spam['color'] = 'black'
>>> spam
['cat', 'chicken', 'dog', 'bat'] The setdefault() method offers a way to do this in one line of code. The first
argument passed to the method is the key to check for, and the second
argument is the value to set at that key if the key does not exist. If the key does
sort():Lists of number values or lists of strings can be sorted with the sort()
exist, the setdefault() method returns the key’s value.
method. For example, enter the following into the interactive shell:
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam = {'name': 'Pooka', 'age': 5}
>>> spam.sort()
>>> spam.setdefault('color', 'black')
>>> spam
'black'
[-7, 1, 2, 3.14, 5]
>>> spam
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.sort()
>>> spam.setdefault('color', 'white')
>>> spam
'black'
['ants', 'badgers', 'cats', 'dogs', 'elephants']
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
5. Explain with a programming example to each:
(i) get ()
(ii)setdefault()
get () Method
It’s tedious to check whether a key exists in a dictionary before accessing that
key’s value. Fortunately, 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.
6. Explain the following methods in list with an examples: 7. Develop suitable Python programs with nested lists to explain copy.copy()
and copy.deepcopy( ) methods.
(i)len() (ii)sum() (iii)max() (iv)min()
If the function modifies the list or dictionary that is passed, you may not want
(i)len() : The len() function will return the number of values that are in a these changes in the original list or dictionary value. For this, Python provides
list value passed to it, just like it can count the number of characters in a string a module named copy that provides both the copy () and deepcopy() functions.
value. The first of these, copy.copy(), can be used to make a duplicate copy of a
>>> spam = ['cat', 'dog', 'moose'] mutable value like a list or dictionary, not just a copy of a reference.
>>> len(spam) >>> import copy
3 >>> spam = ['A', 'B', 'C', 'D']
>>> cheese = copy.copy(spam)
(ii)sum():Python's built-in function sum() is an efficient and Pythonic way to >>> cheese[1] = 42
sum a list of numeric values. >>> spam
['A', 'B', 'C', 'D']
numbers = [1,2,3,4,5,1,4,5] >>> cheese
Sum = sum(numbers) ['A', 42, 'C', 'D']
print(Sum) Now the spam and cheese variables refer to separate lists, which is why only
the list in cheese is modified when you assign 42 at index 7. As you can see
Output: 25 in Figure , the reference ID numbers are no longer the same for both variables
because the variables refer to independent list.
(iii)max():The max() function returns the item with the highest value, or the
item with the highest value in a list.
a = [1, 5, 3, 9]
x = max(a)

print(x)

output: 9

(iv)min():The min() function returns the item with the lowest value, or the
item with the lowest value in an iterable.
If the values are strings, an alphabetically comparison is done.
a = [1, 5, 3, 9]
x = min(a)

print(x) If the list you need to copy contains lists, then use the copy.deepcopy()
output: 1 function instead of copy.copy(). The deepcopy() function will copy these
inner lists as well.
3. Write a python program to accept n numbers and store them in a list.
8. Explain the use of in operator and not in operators in list with suitable Then print the list without ODD numbers in it.
examples.
lst = [ ]
The in and not in Operators
You can determine whether a value is or isn’t in a list with the in and not in n = int(input("Enter number of elements : "))
Operators. for i in range(0, n):
Like other operators, in and not in are used in expressions and connect two ele = int(input())
values: a value to look for in a list and the list where it may be found. lst.append(ele)
These expressions will evaluate to a Boolean value. print(lst)
for i in lst:
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
if i % 2 != 0:
True
lst.remove(i)
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
print("List after removing ODD numbers:")
>>> 'cat' in spam
print(lst)
False
>>> 'howdy' not in spam
Output: Enter number of elements: 5
False
1
>>> 'cat' not in spam
2
True
3
4
myPets = ['Zophie', 'Pooka', 'Fat-tail']
5
print('Enter a pet name:')
[1, 2, 3, 4, 5]
name = input()
List after removing ODD numbers:
if name not in myPets:
[2, 4]
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.') 4. Develop a python program to swap cases of a given string.
The output may look something like this: Input: Java
Enter a pet name: Output: jAVA
Footfoot
I do not have a pet named Footfoot string = "Java"

# prints after swapping all cases


print(string.swapcase())

Input: Java
Output: jAVA

You might also like