0% found this document useful (0 votes)
13 views10 pages

Module - 2 VTU QP and Solution: ('A', 'B', 'C', 'D') ('A', 42, 'C', 'D')

The document provides an overview of various Python programming concepts, including the differences between copy.copy() and copy.deepcopy(), list methods (append, insert, sort, pop, remove), and the characteristics of tuples and dictionaries. It also includes examples of how to manipulate strings, count occurrences of characters, and create functions for specific tasks like displaying a tic-tac-toe board. Additionally, it covers augmented assignment operators and methods like set() and setdefault() in dictionaries.

Uploaded by

forf7627
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)
13 views10 pages

Module - 2 VTU QP and Solution: ('A', 'B', 'C', 'D') ('A', 42, 'C', 'D')

The document provides an overview of various Python programming concepts, including the differences between copy.copy() and copy.deepcopy(), list methods (append, insert, sort, pop, remove), and the characteristics of tuples and dictionaries. It also includes examples of how to manipulate strings, count occurrences of characters, and create functions for specific tasks like displaying a tic-tac-toe board. Additionally, it covers augmented assignment operators and methods like set() and setdefault() in dictionaries.

Uploaded by

forf7627
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/ 10

Module -2 VTU QP and solution

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)

The copy Module’s copy() and deepcopy() Functions


Python provides a module named copy that provides both the copy() and deepcopy() functions.
The first of these, copy.copy(), can be used to make a duplicate copy of a mutable value like a list or
dictionary, not just a copy of a reference.
If the list you need to copy contains lists, then use the copy.deepcopy() function instead of copy.copy().
The deepcopy() function will copy these inner lists as well.

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)

The list data type


• A list is a value that contains multiple values in an ordered sequence.

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

append() - Adding Values to Lists with the append() Method.


Example:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append(‘rat')
>>> spam
['cat', 'dog', 'bat', ‘rat']

insert() - Adding Values to Lists with the insert() Method.

Example:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'rat')
>>> spam
['cat', 'rat', 'dog', 'bat']

sort() - Sorting the Values in a List with the sort() Method


Examples:
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'bats', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'bats', 'cats', 'dogs', 'elephants']

Python List pop() Method

The pop() method removes the element at the specified position.

>>>fruits = ['apple', 'banana', 'cherry']

>>>fruits.pop(1)
'banana'

>>>fruits = ['apple', 'banana', 'cherry']

>>>x = fruits.pop(1)

>>>x

'banana'

>>>fruits

['apple', 'cherry']

remove() - Removing Values from Lists with remove()

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)

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


Example:
>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)

5. Discuss get(), item(), keys() and values() Dictionary methods in python with examples.
(Jan/Feb 2021 – 8M)

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().

• 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

>>> for i in spam.items():


print(i)
Output:
('color', 'red')
('age', 42)
The get() Method
• Python get() method return the value for the given key if present in the dictionary.

• If not, then it will return None.


Syntax:
dictionary.get(keyname, value) Parameter Values Parameter

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)

The list data type


• A list is a value that contains multiple values in an ordered sequence.
• 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 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]

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam
['cat', 'bat', 'rat', 'elephant']

Getting Sublists with Slices


Just as an index can get a single value from a list.
A slice can get several values from a list, in the form of a new list.
A slice is typed between square brackets, like an index, but it has two integers separated by a colon.
spam[2] is a list with an index (one integer).
spam[1:4] is a list with a slice (two integers).
spam[1:4]
• In a slice, the first integer is the index where the slice starts & the second integer is the index where the slice
ends.

• Note: A slice goes up to, but will not include, the value at the second index.

• A slice evaluates to a new list value.


Examples:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[0:-1]
['cat', 'bat', 'rat']
>>> spam[::]
['cat', 'bat', 'rat', 'elephant']
>>>spam[1::]
['bat', 'rat', 'elephant']
>>>spam[::-1]
[‘elephant’,’rat’,’bat’]
>>>spam[1:3]
['bat', 'rat']
>>>spam[1:-1]
['bat', 'rat']

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.

• In code, a dictionary is typed with braces, { }.

Example:
>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
• 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.

>>> myCat['size']
'fat'
Dictionaries vs. Lists
• Items in dictionaries are unordered.

• The first item in a list named spam would be spam[0].

• But there is no “first” item in a dictionary.

• 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

Python program for counting how often each character appears.

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

15. Explain Augmented shorthand assignment operators with an example

Augmented Assignment operators


Examples:
>>> spam = 42
>>> spam = spam + 1
>>> spam
43

Replace With
>>> spam = 42
>>> spam += 1
>>> spam
43
The augmented assignment operators for the +, -, *, /, and % operators
Augmented assignment statement Equivalent assignment statement

spam = spam + 1 spam += 1

spam = spam - 1 spam -= 1

spam = spam * 1 spam *= 1

spam = spam / 1 spam /= 1

spam = spam % 1 spam %= 1

• 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!'

>>> bacon = ['Zophie']


>>> bacon *= 3
>>> bacon
['Zophie', 'Zophie', 'Zophie']
16. Explain set() and setdefault() method in dictionary.
Set() with dictionary
When a dictionary is converted into a set using set(), only the keys are stored in the set. The values are
ignored unless explicitly extracted and converted. This method is useful when working with unique keys
from a dictionary.
d = {'a': 1, 'b': 2, 'c': 3}
a = set(d)
print(a)

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 :

Dictionary1 = { 'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}Third_value =

Dictionary1.setdefault('C') print("Dictionary:", Dictionary1)

print("Third_value:", Third_value)

Output:

Dictionary: {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}Third_value: Geeks

You might also like