Module - 2 VTU QP and Solution: ('A', 'B', 'C', 'D') ('A', 42, 'C', 'D')
Module - 2 VTU QP and Solution: ('A', 'B', 'C', 'D') ('A', 42, 'C', 'D')
1. What is the difference between copy.copy() and copy.deepcopy() function applicable to a list or
dictionary in python? Give suitable examples for each. (July/August 2022 – 6M)
1.Copy()
>>>import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']
2.deepcopy()
>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]
2. Write a python program to swap cases of a given string. (July/August 2022 – 4M)
Input: Java Output: jAVA
In VTU QPs programs
3.What is List? Explain append(), insert(), sort(), pop() and remove() methods with examples.
(Jan/Feb 2021 – 8M)
• A list begins with an opening square bracket and ends with a closing square bracket, [].
• The value [ ] is an empty list that contains no values, similar to ‘ ’, the empty string.
Examples:
>>> [1, 2, 3]
[1, 2, 3]
Example:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'rat')
>>> spam
['cat', 'rat', 'dog', 'bat']
>>>fruits.pop(1)
'banana'
>>>x = fruits.pop(1)
>>>x
'banana'
>>>fruits
['apple', 'cherry']
Examples:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
4. How is tuple different from a list and which function is used to convert list to tuple.
(Jan/Feb 2021 – 5M)
The Tuple Data Type
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 ].
Tuples are different from lists is that tuples, like strings, are immutable (Tuples cannot have their values
modified, appended, or removed).
'tuple' object does not support item assignment
• If you have only one value in your tuple, you can indicate this by placing a trailing comma after the value
inside the parentheses.
Example:
>>> eggs = ('hello', 42, 0.5)
5. Discuss get(), item(), keys() and values() Dictionary methods in python with examples.
(Jan/Feb 2021 – 8M)
• The values returned by these methods are not true lists: They cannot be modified and do not have an
append() method.
• But these data types can be used in for loops.
Example 1:
>>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():
print(v)
Output:
red 42
>>> for k in spam.keys():
print(k)
Output: color age
keyname
Description
Required. The keyname of the item you want to return the value.
Value
Optional. A value to return if the specified key does not exist. Default value None
Example 1:
car = {
"brand": "Ford",
"model": "Mustang", "year": 1964
}
x = car.get("model") print(x)
Output:
Mustang
6. Create a function to print out a blank tic-tac-toe board. (Jan/Feb 2021 – 7M)
In VTU QP programs
7. Develop a program to accept a sentence from the user and display the longest word of that sentence
along with its length. (Jan/Feb 2021 – 6M)
In VTU QP programs
8. What is List? Explain the concept of List Slicing with example. (July/August 2022 – 6M)
• Items are separated with commas (that is, they are comma-delimited).
• The value [ ] is an empty list that contains no values, similar to ‘ ’, the empty string.
Examples:
>>> [1, 2, 3]
[1, 2, 3]
• Note: A slice goes up to, but will not include, the value at the second index.
9. What is Dictionary? How it is different from list? Write s program to count the number of
occurrences of character in a string. (July/August 2022 – 7M)
The dictionary data type:
• Like a list, a dictionary is a collection of many values.
• But unlike indexes for lists, 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.
Example:
>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
• This assigns a dictionary to the myCat variable.
• The values for these keys are 'fat', 'gray', and 'loud', respectively.
>>> myCat['size']
'fat'
Dictionaries vs. Lists
• Items in dictionaries are unordered.
• The order of items matters for determining whether two lists are the same.
• It does not matter in what order the key-value pairs are typed in a dictionary.
Examples:
>>> d1 = ['cats', 'dogs', 'moose']
>>> d2 = ['dogs', 'moose', 'cats']
>>> d1 == d2
False
>>> d3 = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> d4 = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> d3 == d4
True
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
Output:
{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l':
3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}
10. Write a python program that accepts a sentence and find the number of words, digits, uppercase
letters and lowercase letters. (July/August 2022 – 7M)
In VTU QP programs
11. What is a List? Explain the methods that are used to delete items from the List. (Feb / Mar 2022 –
8M)
Answer in Q3.
Methods to delete items from the List:
1. remove()
2. pop()
Removing Values from Lists with del Statements
The del statement will delete values at an index in a list.
All of the values in the list after the deleted value will be moved up one index.
Example
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
12. Write a program to take a sentence as input and display the longest word in the given sentence.
(Feb / Mar 2022 – 6M)
In VTU QP programs
13. How is Dictionary different from list? Assume a Dictionary containing city and population as key
and value respectively. Write a program to traverse the dictionary and display most populous city.
(Feb / Mar 2022 – 6M)
Answer in Q9
name={‘Japan’:720,’Australia’:824,’England’: 560}
new_val = name.values()
max_val= max(new_val)
print(“the most populous city is having population of:”, max_val)
def max_population(d):
# Use the 'max' function to find the key corresponding to the maximum values in the dictionary.
# The 'key' argument specifies that the key should be determined based on the values using 'd.get'.
return max(d, key=d.get)
print("the most populous city is:" + max_population(name)+ " " +"with maximum population of:"+" "+
str(max(name.values())))
Output:
the most populous city is having population of: 824
the most populous city is:Australia with maximum population of: 824
14. Write a program to create a list of number and display the count of even and odd numbers in the
list. (Feb / Mar 2022 – 6M)
In VTU QP programs
Replace With
>>> spam = 42
>>> spam += 1
>>> spam
43
The augmented assignment operators for the +, -, *, /, and % operators
Augmented assignment statement Equivalent assignment statement
• The += operator can also do string and list concatenation, and the *= operator can do
stringand list replication.
• Example
>>> spam = 'Hello'
>>> spam += ' world!'
>>> spam
'Hello world!'
output:
{'b', 'a', 'c'}
Output order may vary.
setdefault() method
• In Python Dictionary, setdefault() method returns the value of a key (if the key is
indictionary).
• If not, it inserts key with a value to the dictionary.
Syntax
dictionary.setdefault(keyname, value)
Parameter Values
Param Description
eter
keynam Required. The keyname of the item you want to
e return the valuefrom
value Optional.
* If the key exist, this parameter has
no effect.
* If the key does not exist, this value becomes
the key's value
* Default value None
Example :
print("Third_value:", Third_value)
Output: