0% found this document useful (0 votes)
41 views6 pages

Python Copy, List, and Dictionary Methods

The document provides a series of questions and answers related to Python programming concepts, including the differences between copy and deepcopy functions, list methods, tuple characteristics, dictionary methods, and various programming tasks. It includes examples for each concept, demonstrating how to manipulate lists, dictionaries, and strings in Python. Additionally, it covers practical programming exercises such as counting characters, finding the longest word in a sentence, and determining the most populous city from a dictionary.
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)
41 views6 pages

Python Copy, List, and Dictionary Methods

The document provides a series of questions and answers related to Python programming concepts, including the differences between copy and deepcopy functions, list methods, tuple characteristics, dictionary methods, and various programming tasks. It includes examples for each concept, demonstrating how to manipulate lists, dictionaries, and strings in Python. Additionally, it covers practical programming exercises such as counting characters, finding the longest word in a sentence, and determining the most populous city from a dictionary.
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

Module -2 VTU QP and solution

1. What is the difference between [Link]() and [Link]() 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, [Link](), 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 [Link]() function instead of [Link]().
The deepcopy() function will copy these inner lists as well.

[Link]()
>>>import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = [Link](spam)
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']

[Link]()
>>> import copy
>>> b = [Link](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

[Link] is List? Explain append(), insert() 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']
>>> [Link](‘rat')
>>> spam
['cat', 'dog', 'bat', ‘rat']

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

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

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

Examples:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> [Link]('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 [Link]():
print(v)
Output:
red 42
>>> for k in [Link]():
print(k)
Output: color age

>>> for i in [Link]():


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:
[Link](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 = [Link]("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:
[Link](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.
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 = [Link]()
max_val= max(new_val)
print(“the most populous city is:”, 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 '[Link]'.
return max(d, key=[Link])
print("the most populous city is:" + max_population(name)+ " " +"with maximum population of:"+" "+
str(max([Link]())))
Output:
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

You might also like