PythonPlaza - Python & AI

Python Quiz

1) what is the output of following code?
lst=["1","2","3"]

del lst[10:100]
print(lst)

a) ['1','2','3']
b) Gives Error
c) 123
d) "1" "2" "3" "4"

Ans) a is correct answer, because lst[10:100] is not found to delete an element

2) What is the output of the following code?

lst =[1,2,3,4,5]
print(lst[25])

a)[]
b)12345
c)Give an Error
d)No output produced.

Ans) c

3) What is the output of the following:

numbers = [5, 6, 7, 8, 9]
for i in range(len(numbers) - 1, -1, -1):
print(numbers[i], end=' ')

a) 98765
b) 56789
c) 12345
d) Gives Error

Ans)a

4)What is the output of the following?

lst=[1,2,3,4,5,6,7,8]
lst1=lst[2:9]
print(lst1)

a) It gives Error
b) [1,2,3,4,5,6,7,8]
c) [3,4,5,6,7,8]
d) []

Ans) c

5)Which symbol is used in python to add comments?

a)$
b)//
c)/*.... */
d)#

Ans) d


6) What is the output of the following code?

def funct(message, n):
while(n > 0):
print(message)
n-=1
funct('A', 5)

a)AAAA
b)AAAAA
c)Syntax Error
d)Infinite Loop

Ans) d - Infinite Loop

7) Find the output of the following program:

myList = ['1', '2', '3', '4', '5']
print(myList[10:])

a)[]
b)[1,2,3]
c)It gives Error.
d)1,2,3,4,5

Ans) a

8) What is the output of the following?

lst=[1,2,3,4,5]
lst.remove(11)
print(lst)

a)[1,2,3,4,5]
b)1,2,3,4,5
c)[]
d)ValueError:

Ans) d

9) What is the output of the following?

lst=[1,2,3,4,5]
del lst[9:10]
print(lst)

a)[1, 2, 3, 4, 5]
b)Gives Error
c)1,2,3,4,5
d)[]
Ans) a

10)What is the output of the following?

A=[1,2,3,4,5]
B=A[:]

print(B)

a)1,2,3,4,5
b)[1,2,3,4,5]
c)Gives Error
d)[5,4,3,2,1]

Ans)b 1. Describe Python Dictionary
A Python dictionary is an unordered, mutable collection consisting key-value pairs where each key must be unique and it has a specific value.

Example:
dict = {'name': 'Mike', 'age': 15}

2. Show how to access a value from a dictionary?
A value in a Python dictionary can be accessed by using the key inside square brackets[].

Example:

dict = {'name' : 'John' , 'age' : '18'}
print(dict['name'])

3. Can you access a non-existent key in Python Dictionary?

Python raises a KeyError if you access a non-existent key, because the key does not exist in the dictionary.

Example:

dict = {'name': 'Amy'}
print(dict['age']) # Raises KeyError: 'age'

4. Show how to avoid a KeyError while accessing a dictionary?
Ans) There are 2 ways to avoid the KetError while accessing a dictionary
a)Use the get() method. It returns None if the key is not found and does not raise an error.
b) use if condition for the key
Example:
dict = {'name': 'Alice'}

if('age' in dict):
print(dict['age'])
else:
print('Key not found')

5. Show how to add or update a key-value pair in a dictionary?

Ans) We can assign a value to key. Its value is updated if the key exists and if it does not exist, a new key-value pair is added to the dictionary.

Example:
dict = {'name': 'Bruce'}
# This adds new key-value pair
dict['age'] = 21
# This updates the value of age
dict['age'] = 25

6.How do you remove a key-value pair from a dictionary?
We can use del or the pop() method to remove a key-value pair from Python Dictionary. pop() method returns the value associated with the key.

Example:
dict= {'name': 'Joseph', 'age': 40}
# Removes 'age' key
del dict['age']
# Removes key 'name' and returns its value
dict.pop('name')

7. How to get all the keys, values, or items in a dictionary?
Use the method keys() to get all keys. Use the method values() to get all values. Use the method items() to key-value pairs. Example: dict = {'name': 'Vincent', 'age': 25} ​ #get all keys() my_dict.keys() #get all values of keys dict.values() #get key-value pairs dict.items() 9. In Python dictionary, can you check if a key exists? Ans) Yes, we can check using if statement dict = {'name': 'Mary', 'age': 19} if ('name' indict): print("Key exists!") 10. What nested dictionary in Python? A dictionary which has atleast a key whose value is another dictionary. Example: dict = {'person': {'name': 'Jack', 'age': 21}, 'address': {'1154 Park Lane, Newark, CA, 94560'}} ​ 11. Give a difference between a Python dictionary and a list. A Python dictionary is an unordered collection of key-value pairs. Python list is an ordered collection of elements. Dictionaries are very efficient for fast key lookups. 12. What method is used to clear all elements from a dictionary? clear() method to remove all key-value pairs. Example: dict = {'name': 'Randy', 'age': 33} ​ #clears all items dict.clear() 13. How do you copy a dictionary? The copy() method creates a shallow copy of the dictionary, which means it copies the dictionary structure itself but does not copy any nested objects. Example: dict = {'name': 'Jack', 'age': 30} ​ #Using copy() dict_copy = dict.copy() 14.Show how to iterate over a dictionary? We can iterate over a dictionary using a for loop using items() to iterate over both keys and values. Example: dict = {'name': 'Jack', 'age': 21} for key, value in dict.items(): print(f"{key}: {value}") 15. What is the difference between pop() and popitem() in Python dictionary? Use pop() to remove a key-value pair by the key and returns its value. Use popitem() to remove and return a random key-value pair 16. How to merge two dictionaries? Use update() Example: dictionary1 = {'name': 'Alice'} dictionary2 = {'age': 25} dictionary1.update(dictionary2) # Merges dictionary2 into dictionary1 ​ 19. What is the purpose of the fromkeys() method? The fromkeys() method creates a new dictionary from a sequence of keys,and assign None values to them Example: my_keys = ['A', 'B', 'C'] ​ #Using fromkeys my_dict = dict.fromkeys(my_keys) 20. What is enumerate function inside a dictionary? Enumerate function is used to get position index and corresponding index at the same time. Example: dict = {'name' : 'Martin', 'age' : 28} for i ,x in enumerate(dict): print(f"{i} - {x}) output: -------- 0 - name 1 - age 21. What is a defaultdict? A defaultdict is a subclass of dict that provides a default value if a key is not found. We can initialize with a factory function. Example: from collections import defaultdict my_dict = defaultdict(int) # Default value is 0 for missing keys my_dict['a'] += 1 22. Can dictionary keys be numbers Yes, dictionary keys can be numbers Example: dict={1:12,2:14} print(dict) output: ------ {1: 12, 2: 14} 23. How do you check the size of a dictionary? Use the len() function to get the number of key-value pairs in a dictionary. Example dict = {'name': 'Amber', 'age': 32} print(len(my_dict)) output: 2 24. Show how to access values in a nested dictionary? nested_dict = {'person': {'name': 'Ronny', 'age': 30}, 'address': {'111 Park street, Newark, CA'}} print(nested_dict['person']['name']) 25. What is the difference between shallow copy and deep copy of a dictionary? There is a basic difference between a Shallow and a deep copy is - A shallow copy copies the dictionary structure but not the nested objects 26. How do you efficiently update a dictionary using another dictionary? The update() method updates the dictionary with the keys and values from another dictionary Example: dict1 = {'name': 'Alice'} dict2 = {'age': 25} dict1.update(dict2) print(dict1) 27) What is the difference between a mutable data type and an immutable data type? Mutable data types: Definition: Mutable data types are those that can be modified after their creation. Examples: List, Dictionary, Set. Immutable data types are those that cannot be modified after their creation. Examples: Numeric (int, float), String, Tuple.