Thursday, January 7, 2021

Python Set Interview questions - Multiple choice

Set Interview questions :

========================================================================

 1. Which of these about a set is not true?

a) Mutable data type

b) Not Allows duplicate values

c) Data type with unordered values

d) Immutable data type


Answer: d

Explanation: A set is a mutable data type with non-duplicate, unordered values, providing the usual mathematical set operations.


2. Which of the following is not the correct syntax for creating a set?

a) set([[1,2],[3,4]])

b) set([1, 2, 2, 3, 4])

c) set((1, 2,3,4))

d) {1, 2, 3, 4}


Answer: a

Explanation: The argument given for the set must be iterable.


3. What will be the output of the following Python code?

nums = set([1,1,2,3,3,3,4,4])

print(len(nums))

a) 7

b) Error, invalid syntax for formation of set

c) 4

d) 8


Answer: c

Explanation: A set doesn’t have duplicate items.


4. Which of the following statements is used to create an empty set?

a) { }

b) set()

c) [ ]

d) ( )


Answer: b

Explanation: { } creates a dictionary not a set. Only set() creates an empty set.


5. What will be the output of the following Python code?

>>> a={5,4}

>>> b={1,2,4,5}

>>> a<b

a) {1,2}

b) True

c) False

d) Invalid operation


Answer: b

Explanation: a<b returns True if a is a proper subset of b.


6. If a={5, 6, 7, 8}, which of the following statements is false?

a) print(len(a))

b) print(min(a))

c) a.remove(5)

d) a[2]=45


Answer: d

Explanation: The members of a set can be accessed by their index values since the elements of the set are unordered.


7.  What will be the output of the following Python code?

>>> a={3, 4, 5}

>>> a.update([1, 2, 3])

>>> print(a)

a) Error, no method called update for set data type

b) {1, 2, 3, 4, 5}

c) Error, list can’t be added to set

d) Error, duplicate item present in list


Answer: b

Explanation: The method update adds elements to a set.


8. If a = {5, 6, 7}, what happens when a.add(5) is executed?

a) a={5, 5, 6, 7}

b) a={5, 6, 7}

c) Error as there is no add function for set data type

d) Error as 5 already exists in the set


Answer: b

Explanation: 5 isn’t added again to the set and the set consists of only non-duplicate elements and 5 already exist in the set.


9. What will be the output of the following Python code?

>>> a = {4, 5, 6}

>>> b={2, 8, 6}

>>> a+b

a) {4,5,6,2,8}

b) {4,5,6,2,8,6}

c) Error as unsupported operand type for sets

d) Error as the duplicate item 6 is present in both sets


Answer: c

Explanation: Execute in python shell to verify.


10. What will be the output of the following Python code?

>>> a={4,5,6}

>>> b={2,8,6}

>>> a-b

a) {4, 5}

b) {6}

c) Error as unsupported operand type for set data type

d) Error as the duplicate item 6 is present in both sets


Answer: a

Explanation: – operator gives the set of elements in set a but not in set b.


12. What will be the output of the following Python code?

>>> s = {5,6}

>>> s*3

a) Error as unsupported operand type for set data type

b) {5,6,5,6,5,6}

c) {5,6}

d) Error as multiplication creates duplicate elements which isn’t allowed


Answer: a

Explanation: The multiplication operator isn’t valid for the set data type.


13. What will be the output of the following Python code?

>>> a = {5, 6, 7, 8}

>>> b = {7, 5, 6, 8}

>>> a == b

a) True

b) False


Answer: a

Explanation: It is possible to compare two sets and the order of elements in both 

the sets don’t matter if the values of the elements are the same.


14. What will be the output of the following Python code?

>>> a={3, 4, 5}

>>> b={5, 6, 7}

>>> a|b  # union

a) Invalid operation

b) {3, 4, 5, 6, 7}

c) {5}

d) {3,4,6,7}


Answer: d

Explanation: The operation in the above piece of code is a union operation. 

This operation produces a set of elements in both set a and set b.


15. Is the following Python code valid?

a={3,4,{7,5}}

print(a[2][0])

a) Yes, 7 is printed

b) Error, elements of a set can’t be printed

c) Error, subsets aren’t allowed

d) Yes, {7,5} is printed


Answer: c

Explanation: In python, elements of a set must not be mutable and sets are mutable. Thus, subsets can’t exist


16. Which of these about a frozenset is not true?

a) Mutable data type

b) Allows duplicate values

c) Data type with unordered values

d) Immutable data type


Answer: a

Explanation: A frozenset is an immutable data type


17. What is the syntax of the following Python code?

>>> a=frozenset(set([5,6,7]))

>>> a

a) {5,6,7}

b) frozenset({5,6,7})

c) Error, not possible to convert set into frozenset

d) Syntax error


Answer: b

Explanation: The above piece of code is the correct syntax for creating a frozenset.


18. Is the following Python code valid?

>>> a=frozenset([5,6,7])

>>> a

>>> a.add(5)

a) Yes, now a is {5,5,6,7}

b) No, frozen set is immutable

c) No, invalid syntax for add method

d) Yes, now a is {5,6,7}


Answer: b

Explanation: Since a frozen set is immutable, add method doesn’t exist for frozen method.


19. Set members must not be hashable.

a) True

b) False


Answer: b

Explanation: Set members must always be hashable.


20. What will be the output of the following Python code?

>>> a={1,2,3}

>>> a.intersection_update({2,3,4,5})

>>> a

a) {2,3}

b) Error, duplicate item present in list

c) Error, no method called intersection_update for set data type

d) {1,4,5}


Answer: a

Explanation: The method intersection_update returns a set that is an intersection of both sets.


21. What will be the output of the following Python code?

>>> a={1,2,3}

>>> b=a

>>> b.remove(3)

>>> a

a) {1,2,3}

b) Error, copying of sets isn’t allowed

c) {1,2}

d) Error, invalid syntax for remove


Answer: c

Explanation: Any change made in b is reflected in a because b is an alias of a.


22. What will be the output of the following Python code?

>>> a={1,2,3}

>>> b=a.copy()

>>> b.add(4)

>>> a

a) {1,2,3}

b) Error, invalid syntax for add

c) {1,2,3,4}

d) Error, copying of sets isn’t allowed


Answer: a

Explanation: In the above piece of code, b is barely a copy and not an alias of a. Hence any change made in b isn’t reflected in a.


23. What will be the output of the following Python code?

>>> a={1,2,3}

>>> b=a.add(4)

>>> b


a) None

b) {1,2,3,4}

c) {1,2,3}

d) Nothing is printed


Answer: d

Explanation: The method add returns nothing, hence nothing is printed.


24. What will be the output of the following Python code?

>>> a={1,2,3}

>>> b=frozenset([3,4,5])

>>> a-b

a) {1,2}

b) Error as difference between a set and frozenset can’t be found out

c) Error as unsupported operand type for set data type

d) frozenset({1,2})


Answer: a

Explanation: – operator gives the set of elements in set a but not in set b


25. What will be the output of the following Python code?

>>> a={5,6,7}

>>> sum(a,5)

a) 5

b) 23

c) 18

d) Invalid syntax for sum method, too many arguments


Answer: b

Explanation: The second parameter is the start value for the sum of elements in set a. Thus, sum(a,5) = 5+(5+6+7)=23


26. What will be the output of the following Python code?

>>> a={1,2,3}

>>> {x*2 for x in a|{4,5}}


a) {2,4,6}

b) Error, set comprehensions aren’t allowed

c) {8, 2, 10, 4, 6}

d) {8,10}


Answer: c

Explanation: Set comprehensions are allowed.


13. What will be the output of the following Python code?


>>> a={5,6,7,8}

>>> b={7,8,9,10}

>>> len(a+b)


a) 8

b) Error, unsupported operand ‘+’ for sets

c) 6

d) Nothing is displayed


Answer: b

Explanation: Duplicate elements in a+b is eliminated and the length of a+b is computed.


14. What will be the output of the following Python code?


a={1,2,3}

b={1,2,3}

c=a.issubset(b)

print(c)


a) True

b) Error, no method called issubset() exists

c) Syntax error for issubset() method

d) False


Answer: a

Explanation: The method issubset() returns True if b is a proper subset of a.


15. Is the following Python code valid?


a={1,2,3}

b={1,2,3,4}

c=a.issuperset(b)

print(c)


a) False

b) True

c) Syntax error for issuperset() method

d) Error, no method called issuperset() exists


Answer: a

Explanation: The method issubset() returns True if b is a proper subset of a.


1. What will be the output of the following Python code?


s=set()

type(s)


a) <’set’>

b) <class ‘set’>

c) set

d) class set


Answer: b

Explanation: When we find the type of a set, the output returned is: .


2. The following Python code results in an error.


s={2, 3, 4, [5, 6]}


a) True

b) False


Answer: a

Explanation: The set data type makes use of a principle known as hashing. 

This means that each item in the set should be hashable. Hashable in this context means immutable. List is mutable and hence 

the line of code shown above will result in an error


3. Set makes use of __________

Dictionary makes use of ____________


a) keys, keys

b) key values, keys

c) keys, key values

d) key values, key values


Answer: c

Explanation: Set makes use of keys.

Dictionary makes use of key values.


4. Which of the following lines of code will result in an error?


a) s={abs}

b) s={4, ‘abc’, (1,2)}

c) s={2, 2.2, 3, ‘xyz’}

d) s={san}


Answer: d

Explanation: The line: s={san} will result in an error because ‘san’ is not defined. 

The line s={abs} does not result in an error because abs is a built-in function. 

The other sets shown do not result in an error because all the items are hashable.


7. Write a list comprehension for number and its cube for:


l=[1, 2, 3, 4, 5, 6, 7, 8, 9]


a) [x**3 for x in l]

b) [x^3 for x in l]

c) [x**3 in l]

d) [x^3 in l]


Answer: a

Explanation: The list comprehension to print a list of cube of the numbers for the given list is: [x**3 for x in l].


8. What will be the output of the following Python code?


s={1, 2, 3}

s.update(4)

s


a) {1, 2, 3, 4}

b) {1, 2, 4, 3}

c) {4, 1, 2, 3}

d) Error


Answer: d

Explanation: The code shown above will result in an error because the argument given to 

the function update should necessarily be an iterable. Hence if we write this function as: s.update([4]), there will be no error.


9. Which of the following functions cannot be used on heterogeneous sets?


a) pop

b) remove

c) update

d) sum


Answer: d

Explanation: The functions sum, min and max cannot be used on mixed type (heterogeneous) sets. 

The functions pop, remove, update etc can be used on homogenous as well as heterogeneous sets. 

An example of heterogeneous sets is: {‘abc’, 4, (1, 2)}


10. What will be the output of the following Python code?


s={4>3, 0, 3-3}

all(s)

any(s)


a)

True

False


b)

False

True


c)

True 

True


d)

False

False


Answer: b

Explanation: The function all returns true only if all the conditions given are true. 

But in the example shown above, we have 0 as a value. Hence false is returned. 

Similarly, any returns true if any one condition is true. Since the condition 4>3 is true, true is returned


11. What will be the output of the following Python code snippet?


z=set('abc$de')

'a' in z

a) True

b) False

c) No output

d) Error


Answer: a

Explanation: The code shown above is used to check whether a particular item is a part of a given set or not. 

Since ‘a’ is a part of the set z, the output is true. Note that this code would result in an error in the absence of the quotes.


12. What will be the output of the following Python code snippet?


z=set('abc')

z.add('san')

z.update(set(['p', 'q']))

z


a) {‘abc’, ‘p’, ‘q’, ‘san’}

b) {‘a’, ‘b’, ‘c’, [‘p’, ‘q’], ‘san}

c) {‘a’, ‘c’, ‘c’, ‘p’, ‘q’, ‘s’, ‘a’, ‘n’}

d) {‘a’, ‘b’, ‘c’, ‘p’, ‘q’, ‘san’}


Answer: d

Explanation: The code shown first adds the element ‘san’ to the set z. 

The set z is then updated and two more elements, namely, ‘p’ and ‘q’ are added to it. 

Hence the output is: {‘a’, ‘b’, ‘c’, ‘p’, ‘q’, ‘san’}


4. What will be the output of the following Python code snippet?


s=set([1, 2, 3])

s.union([4, 5])

s|([4, 5])


a)

   {1, 2, 3, 4, 5}

   {1, 2, 3, 4, 5}


b)

   Error

   {1, 2, 3, 4, 5}


c)

   {1, 2, 3, 4, 5}

   Error


d)

   Error

   Error

   

Answer: c

Explanation: The first function in the code shown above returns the set {1, 2, 3, 4, 5}. 

This is because the method of the function union allows any iterable. 

However the second function results in an error because of unsupported data type, that is list and set.


5. What will be the output of the following Python code snippet?


for x in set('pqr'):

print(x*2)


a)

pp

qq

rr

b)

pqr

pqr

c) ppqqrr

d) pqrpqr


Answer: a

Explanation: The code shown above prints each element of the set twice separately. Hence the output of this code is:

pp

qq

rr


6. What will be the output of the following Python code snippet?


{a**2 for a in range(4)}


a) {1, 4, 9, 16}

b) {0, 1, 4, 9, 16}

c) Error

d) {0, 1, 4, 9}


Answer: d

Explanation: The code shown above returns a set containing the square of values in the range 0-3, 

that is 0, 1, 2 and 3. Hence the output of this line of code is: {0, 1, 4, 9}.


7. What will be the output of the following Python function?


{x for x in 'abc'}

{x*3 for x in 'abc'}


a)

   {abc}

aaa

bbb

ccc


b)

abc

   abc abc abc


c)

{‘a’, ‘b’, ‘c’}

   {‘aaa’, ‘bbb’, ‘ccc’}


d)

{‘a’, ‘b’, ‘c’}

abc

abc

abc


Answer: c

Explanation: The first function prints each element of the set separately, hence the output is: {‘a’, ‘b’, ‘c’}. 

The second function prints each element of the set thrice, contained in a new set. 

Hence the output of the second function is: {‘aaa’, ‘bbb’, ‘ccc’}. (Note that the order may not be the same)


8. The output of the following code is: class<’set’>.


type({})


a) True

b) False


Answer: b

Explanation: The output of the line of code shown above is: class<’dict’>. This is because {} represents an empty dictionary, 

whereas set() initializes an empty set. Hence the statement is false.


9. What will be the output of the following Python code snippet?


a=[1, 4, 3, 5, 2]

b=[3, 1, 5, 2, 4]

a==b

set(a)==set(b)


a)

   True

   False


b)

   False

   False


c)

   False

   True


d)

True

True


Answer: c

Explanation: In the code shown above, when we check the equality of the two lists, a and b, 

we get the output false. This is because of the difference in the order of elements of the two lists. 

However, when these lists are converted to sets and checked for equality, the output is true. 

This is known as order-neutral equality. Two sets are said to be equal if and only if they contain exactly 

the same elements, regardless of order.


10. What will be the output of the following Python code snippet?


l=[1, 2, 4, 5, 2, 'xy', 4]

set(l)

l


a)

{1, 2, 4, 5, 2, ‘xy’, 4}

[1, 2, 4, 5, 2, ‘xy’, 4]


b)


{1, 2, 4, 5, ‘xy’}

[1, 2, 4, 5, 2, ‘xy’, 4]


c)


{1, 5, ‘xy’}

[1, 5, ‘xy’]


d)


{1, 2, 4, 5, ‘xy’}

[1, 2, 4, 5, ‘xy’]


Answer: b

Explanation: In the code shown above, the function set(l) converts the given list into a set. 

When this happens, all the duplicates are automatically removed. Hence the output is: {1, 2, 4, 5, ‘xy’}. 

On the other hand, the list l remains unchanged. Therefore the output is: [1, 2, 4, 5, 2, ‘xy’, 4].

Note that the order of the elements may not be the same.


1. What will be the output of the following Python code?


s1={3, 4}

s2={1, 2}

s3=set()

i=0

j=0

for i in s1:

for j in s2:

s3.add((i,j))

i+=1

j+=1

print(s3)


a) {(3, 4), (1, 2)}

b) Error

c) {(4, 2), (3, 1), (4, 1), (5, 2)}

d) {(3, 1), (4, 2)}


Answer: c

Explanation: The code shown above finds the Cartesian product of the two sets, s1 and s2. 

The Cartesian product of these two sets is stored in a third set, that is, s3. 

Hence the output of this code is: {(4, 2), (3, 1), (4, 1), (5, 2)}.


2. The ____________ function removes the first element of a set and the last element of a list.


a) remove

b) pop

c) discard

d) dispose


Answer: b

Explanation: The function pop removes the first element when used on a set and the last element when used to a list.


3. The difference between the functions discard and remove is that:


a) Discard removes the last element of the set whereas remove removes the first element of the set

b) Discard throws an error if the specified element is not present in the set whereas remove does not throw an error in case of absence of the specified element

c) Remove removes the last element of the set whereas discard removes the first element of the set

d) Remove throws an error if the specified element is not present in the set whereas discard does not throw an error in case of absence of the specified element


Answer: d

Explanation: The function remove removes the element if it is present in the set. If the element is not present, 

it throws an error. The function discard removes the element if it is present in the set. 

If the element is not present, no action is performed (Error is not thrown).


4. What will be the output of the following Python code?


s1={1, 2, 3}

s2={3, 4, 5, 6}

s1.difference(s2)

s2.difference(s1)


a)


{1, 2}

{4, 5, 6}


b)


{1, 2}

{1, 2}


c)


{4, 5, 6}

{1, 2}


d)

{4, 5, 6}

{4, 5, 6}


Answer: a

Explanation: The function s1.difference(s2) returns a set containing the elements 

which are present in the set s1 but not in the set s2. Similarly, the function s2.difference(s1) 

returns a set containing elements which are present in the set s2 but not in the set s1. Hence the output of the code shown above will be:

{1, 2}

{4, 5, 6}.


5. What will be the output of the following Python code?


s1={1, 2, 3}

s2={4, 5, 6}

s1.isdisjoint(s2)

s2.isdisjoint(s1)


a)


True

False


b)


False 

True


c)


True

True


d)


False

False


Answer: c

Explanation: The function isdisjoint returns true the two sets in question are disjoint, that is if they do not have even a single element in common. 

The two sets s1 and s2 do not have any elements in common, hence true is returned in both the cases.


6. If we have two sets, s1 and s2, and we want to check if all the elements of s1 are present in s2 or not, we can use the function:


a) s2.issubset(s1)

b) s2.issuperset(s1)

c) s1.issuperset(s2)

d) s1.isset(s2)


Answer: b

Explanation: Since we are checking whether all the elements present in the set s1 are present in the set s2. 

This means that s1 is the subset and s1 is the superset. Hence the function to be used is: s2.issuperset(s1). This operation can also be performed by the function: s1.issubset(s2).


7. What will be the output of the following Python code?


s1={1, 2, 3, 8}

s2={3, 4, 5, 6}

s1|s2

s1.union(s2)


a)


{3}

{1, 2, 3, 4, 5, 6, 8}


b)


{1, 2, 4, 5, 6, 8}

{1, 2, 4, 5, 6, 8}


c)


{3}

{3}


d)


{1, 2, 3, 4, 5, 6, 8}

{1, 2, 3, 4, 5, 6, 8}


Answer: d

Explanation: The function s1|s2 as well as the function s1.union(s2) returns a union of the two sets s1 and s2. 

Hence the output of both of these functions is: {1, 2, 3, 4, 5, 6, 8}


8. What will be the output of the following Python code?


a=set('abc')

b=set('def')

b.intersection_update(a)

a

b


a)


set()

(‘e’, ‘d’, ‘f’}


b)


{}

{}


c)


{‘b’, ‘c’, ‘a’}

set()


d)


set()

set()


Answer: c

Explanation: The function b.intersection_update(a) puts those elements in the set b which are common to both the sets a and b. 

The set a remains as it is. Since there are no common elements between the sets a and b, the output is:‘b’, ‘c’, ‘a’} set().


9. What will be the output of the following Python code, if s1= {1, 2, 3}?


s1.issubset(s1)


a) True

b) Error

c) No output

d) False


Answer: a

Explanation: Every set is a subset of itself and hence the output of this line of code is true.


10. What will be the output of the following Python code?


x=set('abcde')

y=set('xyzbd')

x.difference_update(y)

x

y


a)


   {‘a’, ‘b’, ‘c’, ‘d’, ‘e’}

   {‘x’, ‘y’, ‘z’}

b)


   {‘a’, ‘c’, ‘e’}

   {‘x’, ‘y’, ‘z’, ‘b’, ‘d’}

c)


   {‘b’, ‘d’}

   {‘b’, ‘d’}

d)


   {‘a’, ‘c’, ‘e’}

   {‘x’, ‘y’, ‘z’}


Answer: b

Explanation: The function x.difference_update(y) removes all the elements of the set y from the set x. 

Hence the output of the code is:{‘a’, ‘c’, ‘e’} {‘x’, ‘y’, ‘z’, ‘b’, ‘d’}.


Request: If you find this information useful, please provide your valuable comments.


Python Dictionary Interview questions - Multiple choice

 Dictionary:

========================================================================

1.Which of the following statements create a dictionary?

a) d = {}

b) d = {“john”:40, “peter”:45}

c) d = {40:”john”, 45:”peter”}

d) All of the mentioned


Answer: d

Explanation: Dictionaries are created by specifying keys and values.


2. What will be the output of the following Python code snippet?

d = {"john":40, "peter":45}

"john" in d

a) True

b) False

c) None

d) Error


Answer: a

Explanation: In can be used to check if the key is in the dictionary.


3. What will be the output of the following Python code snippet?

d1 = {"john":40, "peter":45}

d2 = {"john":466, "peter":45}

d1 == d2

a) True

b) False

c) None

d) Error


Answer: b

Explanation: If d2 was initialized as d2 = d1 the answer would be true.


4. What will be the output of the following Python code snippet?

d1 = {"john":40, "peter":45}

d2 = {"john":466, "peter":45}

d1 > d2

a) True

b) False

c) Error

d) None


Answer: c

Explanation: Arithmetic > operator cannot be used with dictionaries.


5. What will be the output of the following Python code snippet?

d = {"john":40, "peter":45}

d["john"]

a) 40

b) 45

c) “john”

d) “peter”


Answer: a

Explanation: Execute in the shell to verify.


6. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do we use?

a) d.delete(“john”:40)

b) d.delete(“john”)

c) del d[“john”]

d) del d(“john”:40)


Answer: c

Explanation: Execute in the shell to verify.


7. Suppose d = {“john”:40, “peter”:45}. To obtain the number of entries in the dictionary which command do we use?

a) d.size()

b) len(d)

c) size(d)

d) d.len()


Answer: b

Explanation: Execute in the shell to verify.


8. What will be the output of the following Python code snippet?

d = {"john":40, "peter":45}

print(list(d.keys()))

a) [“john”, “peter”]

b) [“john”:40, “peter”:45]

c) (“john”, “peter”)

d) (“john”:40, “peter”:45)


Answer: a

Explanation: The output of the code shown above is a list containing only keys of the dictionary d, in the form of a list.


9. Suppose d = {“john”:40, “peter”:45}, what happens when we try to retrieve a value using the expression d[“rohith”]?

a) Since “rohith” is not a value in the set, Python raises a KeyError exception

b) It is executed fine and no exception is raised, and it returns None

c) Since “rohith” is not a key in the set, Python raises a KeyError exception

d) Since “rohith” is not a key in the set, Python raises a syntax error


Answer: c

Explanation: Execute in the shell to verify.


10. Which of these about a dictionary is false?

a) The values of a dictionary can be accessed using keys

b) The keys of a dictionary can be accessed using values

c) Dictionaries aren’t ordered

d) Dictionaries are mutable


Answer: b

Explanation: The values of a dictionary can be accessed using keys but the keys of a dictionary can’t be accessed using values.


11. Which of the following is not a declaration of the dictionary?

a) {1: ‘A’, 2: ‘B’}

b) dict([[1,”A”],[2,”B”]])

c) {1, "A", 2, "B"}

d) { }


Answer: c

Explanation: Option c is a set, not a dictionary.


12. What will be the output of the following Python code snippet?

a={1:"A", 2:"B", 3:"C"}

print(a.get(1,4))

a) 1

b) A

c) 4

d) Invalid syntax for get method.


Answer: b

Explanation: The get() method returns the value of the key if the key is present in 

the dictionary and the default value(second parameter) if the key isn’t present in the dictionary.


13. What will be the output of the following Python code snippet?

a={1:"A", 2:"B", 3:"C"}

print(a.get(5,4))

a) Error, invalid syntax

b) A

c) 5

d) 4


Answer: d

Explanation: The get() method returns the default value(second parameter) if the key isn’t present in the dictionary.


14. What will be the output of the following Python code snippet?

a={1:"A", 2:"B", 3:"C"}

print(a.setdefault(3))

a) {1: ‘A’, 2: ‘B’, 3: ‘C’}

b) C

c) {1: 3, 2: 3, 3: 3}

d) No method called setdefault() exists for dictionary


Answer: b

Explanation: setdefault() is similar to get() but will set dict[key]=default if key is not already in the dictionary.


15. What will be the output of the following Python code snippet?

a={1:"A",2:"B",3:"C"}

a.setdefault(4,"D")

print(a)

a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’}

b) None

c) Error

d) [1,3,6,10]


Answer: a

Explanation: setdefault() will set dict[key]=default if key is not already in the dictionary.


16. What will be the output of the following Python code?

a={1:"A", 2:"B", 3:"C"}

b={4:"D", 5:"E"}

a.update(b)

print(a)

a) {1: ‘A’, 2: ‘B’, 3: ‘C’}

b) Method update() doesn’t exist for dictionaries

c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’}

d) {4: ‘D’, 5: ‘E’}


Answer: c

Explanation: update() method adds dictionary b’s key-value pairs to dictionary a. Execute in python shell to verify.


17. What will be the output of the following Python code?

a={1:"A", 2:"B", 3:"C"}

b=a.copy()

b[2]="D"

print(a)

a) Error, copy() method doesn’t exist for dictionaries

b) {1: ‘A’, 2: ‘B’, 3: ‘C’}

c) {1: ‘A’, 2: ‘D’, 3: ‘C’}

d) “None” is printed


Answer: b

Explanation: .copy performs deep copy (creates separate memory location)Changes made in the 2nd dictionary aren’t reflected in the original one.


18. What will be the output of the following Python code?

a={1:"A", 2:"B", 3:"C"}

a.clear()

print(a)

a) None

b) { None:None, None:None, None:None}

c) {1:None, 2:None, 3:None}

d) { }


Answer: d

Explanation: The clear() method clears all the key-value pairs in the dictionary.


19. Which of the following isn’t true about dictionary keys?

a) When duplicate keys are encountered, the last assignment wins

b) Keys must be immutable

c) Keys must be integers

d) None


Answer: c

Explanation: Keys of a dictionary may be any data type that is immutable.


20. What will be the output of the following Python code?

a={1:5, 2:3, 3:4}

a.pop(2)

print(a)

a) {1: 5}

b) {1: 5, 2: 3}

c) Error, syntax error for pop() method

d) {1: 5, 3: 4}


Answer: d

Explanation: pop() method removes the key-value pair for the key mentioned in the pop() method.


21. What will be the output of the following Python code?

>>> a={1:"A", 2:"B", 3:"C"}

>>> a.items()

a) Syntax error

b) dict_items([(‘A’), (‘B’), (‘C’)])

c) dict_items([(1,2,3)])

d) dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)])


Answer: d

Explanation: The method items() returns the list of tuples with each tuple having a key-value pair.


22. Which of the statements about dictionary values is false?

a) More than one key can have the same value

b) The values of the dictionary can be accessed as dict[key]

c) Values of a dictionary must be unique

d) Values of a dictionary can be a mixture of letters and numbers


Answer: c

Explanation: More than one key can have the same value.


23. What will be the output of the following Python code snippet?

>>> a={1:"A", 2:"B", 3:"C"}

>>> del a

a) method del doesn’t exist for the dictionary

b) del deletes the values in the dictionary

c) del deletes the entire dictionary

d) del deletes the keys in the dictionary


Answer: c

Explanation: del deletes the entire dictionary and any further attempt to access it will throw an error.


24. If a is a dictionary with some key-value pairs, what does a.popitem() do?

a) Removes an arbitrary element

b) Removes all the key-value pairs

c) Removes the key-value pair for the key given as an argument

d) Invalid method for dictionary


Answer: a

Explanation: The method pop item() removes a random key-value pair.


25. What will be the output of the following Python code snippet?

numbers = letters = narendra= {}

numbers[1] = 56

numbers[3] = 7

letters[4] = 'B'

narendra['Numbers'] = numbers

narendra['Letters'] = letters

print(narendra)

a) Error, dictionary in a dictionary can’t exist

b) ‘Numbers’: {1: 56, 3: 7}

c) {‘Numbers’: {1: 56}, ‘Letters’: {4: ‘B’}}

d) {‘Numbers’: {1: 56, 3: 7}, ‘Letters’: {4: ‘B’}}


Answer: d

Explanation: Dictionary in a dictionary (nested dictionaries) can exist.


26. What will be the output of the following Python code snippet?

test = {1:'A', 2:'B', 3:'C'}

test = {}

print(len(test))

a) 0

b) None

c) 3

d) An exception is thrown


Answer: a

Explanation: In the second line of code, the dictionary becomes an empty dictionary. Thus, length=0.


27. What will be the output of the following Python code snippet?

test = {1:'A', 2:'B', 3:'C'}

del test[1]

test[1] = 'D'

del test[2]

print(len(test))

a) 0

b) 2

c) Error as the key-value pair of 1:’A’ is already deleted

d) 1


Answer: b

Explanation: After the key-value pair of 1:’A’ is deleted, the key-value pair of 1:’D’ is added.


28. What will be the output of the following Python code snippet?

a={}

a['a']=1

a['b']=[2,3,4]

print(a)

a) Exception is thrown

b) {‘b’: [2], ‘a’: 1}

c) {‘b’: [2], ‘a’: [3]}

d) {‘b’: [2, 3, 4], ‘a’: 1}


Answer: d

Explanation: Dictionary is unordered. Mutable members can be used as the values of the dictionary but they cannot be used as the keys of the dictionary.


29. What will be the output of the following Python code?

a = {}

a[2] = 1

a[1] = [2,3,4]   

print(a[1][1])

a) [2,3,4]

b) 3

c) 2

d) An exception is thrown


Answer: (b) 

Explanation: Now, a={1:[2,3,4],2:1} . a[1][1] refers to second element having key 1.


30. What will be the output of the following Python code?

a={'B':5, 'A':9, 'C':7}

sorted(a)

a) [‘A’,’B’,’C’]

b) [‘B’,’C’,’A’]

c) [5,7,9]

d) [9,5,7]


Answer: a

Explanation: Return a new sorted list of keys in the dictionary.


31. What will be the output of the following Python code?

>>> a={}

>>> a.fromkeys( [1, 2, 3], "check")

a) Syntax error

b) {1:”check”, 2:”check”, 3:”check”}

c) “check”

d) {1:None, 2:None, 3:None}


Answer: b

Explanation: The dictionary takes values of keys from the list and initializes them to the default value 

(value is given in the second parameter). Execute in Python shell to verify.


32. What will be the output of the following Python code?

b = {}

all(b)

a) { }

b) False

c) True

d) An exception is thrown


Answer: c

Explanation: Function all() returns True if all keys of the dictionary are true or if the dictionary is empty.


33. If b is a dictionary, what does any(b) do?

a) Returns True if any key of the dictionary is true

b) Method any() doesn’t exist for dictionary

c) Returns True if all keys of the dictionary are true

d) None


Answer: a

Explanation: Method any() returns True if any key of the dictionary is true and False if the dictionary is empty.


34. What will be the output of the following Python code?

        a = {"a":1, "b":2, "c":3}

b = dict(zip(a.values(),a.keys()))

        print(b)

a) {‘a’: 1, ‘b’: 2, ‘c’: 3}

b) An exception is thrown

c) {‘a’: ‘b’: ‘c’: }

d) {1: ‘a’, 2: ‘b’, 3: ‘c’}


Answer: d

Explanation: The above piece of code inverts the key-value pairs in the dictionary.


35. What will be the output of the following Python code?

a = dict()

a[1]

a) An exception is thrown since the dictionary is empty

b) ‘ ‘

c) 1

d) 0


Answer: a

Explanation: The values of a dictionary can be accessed through the keys only if the keys exist in the dictionary.


36. what is the output of the following code snippet?

    dict1 = {'a': 10, 'b': 8}
    dict2 = {'d': 6, 'c': 4}
    print(dict(dict1, **dict2))
Answer: {'a': 10, 'b': 8, 'd': 6, 'c': 4}
========================================================

37. What will be the output of the following Python code?

print(list(zip((1,2,3),('a'),('xxx','yyy'))))

print(list(zip((2,4),('b','c'),('yy','xx'))))

a) [(1,2,3),(‘a’),(‘xxx’,’yyy’)]

[(2,4),(‘b’,’c’),(‘yy’,’xx’)]

b) [(1, 'a', 'xxx'),(2,’ ‘,’yyy’),(3,’ ‘,’ ‘)]

[(2, 'b', 'yy'), (4, 'c', 'xx')]

c) Syntax error

d) [(1, 'a', 'xxx')]

[(2, 'b', 'yy'), (4, 'c', 'xx')]


Answer: d

Explanation: The zip function combines the individual attributes of the lists into a list of tuples.


Request: If you find this information useful, please provide your valuable comments.

 

Python Tuple Interview questions - Multiple choice

 Tuple Interview questions:

========================================================================


1. Suppose t = (1, 2, 4, 3), which of the following is incorrect?

a) print(t[3])

b) t[3] = 45

c) print(max(t))

d) print(len(t))


Answer: b

Explanation: Values cannot be modified in the case of the tuple, that is, a tuple is immutable.


2. What will be the output of the following Python code?

>>>t=(1,2,4,3)

>>>t[1:3]

a) (1, 2)

b) (1, 2, 4)

c) (2, 4)

d) (2, 4, 3)


Answer: c

Explanation: Slicing in tuples takes place just as it does in strings.


3. What will be the output of the following Python code?

>>>t=(1,2,4,3)

>>>t[1:-1]

a) (2, 4, 3)

b) (1, 2, 4)

c) [2, 4]

d) (2, 4) 


Answer: d

Explanation: Slicing in tuples takes place just as it does in strings.


4. What will be the output of the following Python code?

>>>t = (1, 2)

>>> t*2

a) (1, 2, 1, 2)

b) [1, 2, 1, 2]

c) (1, 1, 2, 2)

d) [1, 1, 2, 2]


Answer: a

Explanation: * operator concatenates tuple.


5. What will be the output of the following Python code?

>>>t1 = (1, 2, 4, 3)

>>>t2 = (1, 2, 3, 4)

>>>t1 < t2

a) True

b) False

c) Error

d) None


Answer: b

Explanation: Elements are compared one by one in this case.


6. What will be the output of the following Python code?

>>>my_tuple = (1, 2, 3, 4)

>>>my_tuple.append( (5, 6, 7) )

>>>print len(my_tuple)

a) 1

b) 2

c) 5

d) Error


Answer: d

Explanation: Tuples are immutable and don’t have an append method. An exception is thrown in this case.


7. What is the data type of (1)?

a) Tuple

b) Integer

c) List

d) Both tuple and integer


Answer: b

Explanation: A tuple of one element must be created as (1,).


12. If a=(1,2,3,4), a[1:-1] is _________

a) Error, tuple slicing doesn’t exist

b) [2,3]

c) (2,3,4)

d) (2,3)


Answer: d

Explanation: Tuple slicing exists and a[1:-1] returns (2,3).


13. What will be the output of the following Python code?

>>> a=(1,2,(4,5))

>>> b=(1,2,(3,4))

>>> a<b

a) False

b) True

c) Error, < operator is not valid for tuples

d) Error, < operator is valid for tuples but not if there are sub-tuples


Answer: a

Explanation: Since the first element in the sub-tuple of a is larger than the first element in the sub-tuple of b, False is printed.


14. What will be the output of the following Python code?

>>> a=("Check")*3

>>> a

a) (‘Check’,’Check’,’Check’)

b) * Operator not valid for tuples

c) (‘CheckCheckCheck’)

d) Syntax error


Answer: c

Explanation: Here (“Check”) is a string, not a tuple because there is no comma after the element.


15. What will be the output of the following Python code?

>>> a=(1,2,3,4)

>>> del(a[2])

a) Now, a=(1,2,4)

b) Now, a=(1,3,4)

c) Now a=(3,4)

d) Error as tuple is immutable


Answer: d

Explanation: ‘tuple’ object doesn’t support item deletion.


16. What will be the output of the following Python code?

>>> a=(2, 3, 4)

>>> sum(a, 3)

a) Too many arguments for sum() method

b) The method sum() doesn’t exist for tuples

c) 12

d) 9


Answer: c

Explanation: In the above case, 3 is the starting value to which the sum of the tuple is added.


17. Is the following Python code valid?

>>> a=(1,2,3,4)

>>> del a

a) No because tuple is immutable

b) Yes, first element in the tuple is deleted

c) Yes, the entire tuple is deleted

d) No, invalid syntax for del method


Answer: c

Explanation: The command del a deletes the entire tuple.


18. What type of data is: a=[(1,1),(2,4),(3,9)]?

a) Array of tuples

b) List of tuples

c) Tuples of lists

d) Invalid type


Answer: b

Explanation: The variable has tuples enclosed in a list making it a list of tuples.


19. What will be the output of the following Python code?

>>> a=(0,1,2,3,4)

>>> b=slice(0,2)

>>> a[b]

a) Invalid syntax for slicing

b) [0,2]

c) (0,1)

d) (0,2)


Answer: c

Explanation: The method illustrated in the above piece of code is that of the naming slices.


20. Is the following Python code valid?

>>> a = (1, 2, 3)

>>> b = ('A', 'B', 'C')

>>> c = tuple(zip(a, b))

a) Yes, c will be ((1,2,3),(‘A’,’B’,’C’))

b) Yes, c will be ((1, 'A'), (2, 'B'), (3, 'C'))

c) No because tuples are immutable

d) No because the syntax for zip function isn’t valid


Answer: b

Explanation: The zip function combines individual elements of two iterables into tuples. 


21. Is the following Python code valid?

>>> a, b, c=1, 2, 3

>>> a, b, c

a) Yes, [1,2,3] is printed

b) No, invalid syntax

c) Yes, (1,2,3) is printed

d) 1 is printed


Answer: c

Explanation: A tuple needn’t be enclosed in parenthesis.


 

23. Is the following Python code valid?

>>> a,b=1,2,3

a) Yes, this is an example of tuple unpacking. a=1 and b=2

b) Yes, this is an example of tuple unpacking. a=(1,2) and b=3

c) No, too many values to unpack

d) Yes, this is an example of tuple unpacking. a=1 and b=(2,3)


Answer: c

Explanation: For unpacking to happen, the number of values on the right-hand side must be equal to the number of variables on the left-hand side.


24. What will be the output of the following Python code?

>>> a = (1,2)

>>> b = (3,4)

>>> c = a+b

>>> c

a) (4,6)

b) (1, 2, 3, 4)

c) Error as tuples are immutable

d) None


Answer: b

Explanation: In the above piece of code, the values of the tuples aren’t being changed. 

Both the tuples are simply concatenated.


25. What will be the output of the following Python code?

>>> a, b = 6, 7

>>> a, b = b, a

>>> a, b

a) (6,7)

b) Invalid syntax

c) (7,6)

d) Nothing is printed


Answer: c

Explanation: The above piece of code illustrates the unpacking of variables.


27. Tuples can’t be made keys of a dictionary.

a) True

b) False


Answer: b

Explanation: Tuples can be made keys of a dictionary because they are hashable.


28. Is the following Python code valid?

>>> a=2,3,4,5

>>> a

a) Yes, 2 is printed

b) Yes, [2,3,4,5] is printed

c) No, too many values to unpack

d) Yes, (2,3,4,5) is printed


Answer: d

Explanation: A tuple needn’t be enclosed in parenthesis.


29. What will be the output of the following Python code?

>>> a=(2,3,1,5)

>>> a.sort()

>>> print(a)

a) (1,2,3,5)

b) (2,3,1,5)

c) None

d) Error, tuple has no attribute sort


Answer: d

Explanation: A tuple is immutable thus it doesn’t have a sort attribute.


30. Is the following Python code valid?

>>> a = (1, 2, 3)

>>> b = a.update(4,)

a) Yes, a=(1,2,3,4) and b=(1,2,3,4)

b) Yes, a=(1,2,3) and b=(1,2,3,4)

c) No because tuples are immutable

d) No because wrong syntax for update() method


Answer: c

Explanation: Tuple doesn’t have any update() attribute because it is immutable.


31. What will be the output of the following Python code?

>>> a=[(2,4),(1,2),(3,9)]

>>> a.sort()

>>> print(a)

a) [(1, 2), (2, 4), (3, 9)]

b) [(2,4),(1,2),(3,9)]

c) Error because tuples are immutable

d) Error, tuple has no sort attribute


Answer: d

Explanation: A list of tuples is a list itself. Hence items on a list can be sorted.

Request: If you find this information useful, please provide your valuable comments.

Python List Interview questions - Multiple choice

 List Interview questions:

========================================================================

1. Which of the following commands will create a list?

a) list1 = list()

b) list1 = []

c) list1 = list([1, 2, 3])

d) all of the mentioned


Answer: d

Explanation: Execute in the shell to verify


2. What is the output when we execute list(“hello”)?

a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

b) [‘hello’]

c) [‘llo’]

d) [‘olleh’]


Answer: a

Explanation: Execute in the shell to verify. (Note: it's not a split() function,  type casting is happening.  i.e converting from string to list)


3. Suppose list_example is [‘h’,’e’,’l’,’l’,’o’]  what is len(list_example)?

a) 5

b) 4

c) None

d) Error


Answer: a

Explanation: Execute in the shell and verify.


4. Suppose list1 is [2445, 133, 12454, 123]  what is max(list1)?

a) 2445

b) 133

c) 12454

d) 123


Answer: c

Explanation: Max returns the maximum element in the list.


5. Suppose list_1 is [3, 5, 25, 1, 4]  what is min(list_1)?

a) 3

b) 5

c) 25

d) 1


Answer: d

Explanation: Min returns the minimum element in the list.


6. Suppose list_1 is [1, 5, 9]  what is sum(list_1)?

a) 1

b) 9

c) 15

d) Error


Answer: c

Explanation: Sum returns the sum of all elements in the list.


7. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.count(5)?

a) 0

b) 4

c) 1

d) 2


Answer: d

Explanation: Execute in the shell to verify.


8. Suppose list_1 is [4, 2, 2, 4, 5, 2, 1, 0]

     Which of the following is the correct syntax for slicing operation?

a) print(list_1[0])

b) print(list_1[ :2])

c) print(list_1[ :-2])

d) all of the mentioned


Answer: d

Explanation: Slicing is allowed in lists just as in the case of strings.


9. Suppose list_1 is [2, 33, 222, 14, 25]  What is list_1[-1]?

a) Error

b) None

c) 25

d) 2


Answer: c

Explanation: -1 corresponds to the last index in the list.


10. Suppose list1 is [2, 33, 222, 14, 25] What is list1[ :-1] ?

a) [2, 33, 222, 14, 25] 

b) 25

c) [25, 14, 222, 33, 2]

d) [2, 33, 222, 14]


Answer: d

Explanation: Execute in the shell to verify


11. What will be the output of the following Python code?

>>>names = ["Narendra", "Boyina", "raj", "Mahalakshmi"]

>>>print(names[-1][-1])

a) M

b) Mahalakshmi

c) Error

d) i


Answer: d

Explanation: Execute in the shell to verify.


12. What will be the output of the following Python code?

    names_1 = ["Narendra", "Bhaskarao", "raj", "Mahalakshmi"]
    names_2 = names_1  # shallow copy
    names_3 = names_1[:] # deep copy
    names_2[0] = 'Surendra'
    names_3[1] = "Udaya Bhaskara rao"

    print(names_1)
    print(names_2)
    print(names_3)

    a)  ['Surendra', 'Udaya Bhaskara rao', 'raj', 'Mahalakshmi']
        ['Surendra', 'Udaya Bhaskara rao', 'raj', 'Mahalakshmi']
        ['Narendra', 'Udaya Bhaskara rao', 'raj', 'Mahalakshmi']
    b)  ['Surendra', 'Bhaskarao', 'raj', 'Mahalakshmi']
        ['Surendra', 'Bhaskarao', 'raj', 'Mahalakshmi']
        ['Narendra', 'Udaya Bhaskara rao', 'raj', 'Mahalakshmi']
    c) Error
    d) None of the above



Answer: b

Explanation:  names_1 and names_2 are using the same memory location reason: Shallow copy

        if you change in names_2 it will affect names_1 vice versa       reason: Shallow copy 

       But names_3 used a different memory location reason: Deep copy

      if you do changes in names_3 it will not affect the names_1reason: Deep copy


13. Suppose list_1 is [1, 3, 2] What is list_1 * 2?

a) [2, 6, 4]

b) [1, 3, 2, 1, 3]

c) [1, 3, 2, 1, 3, 2]

d) [1, 3, 2, 3, 2, 1]


Answer: c

Explanation: Execute in the shell and verify.


14. What will be the output of the following Python code?

>>>list1 = [11, 2, 23]

>>>list2 = [11, 2, 2]

>>>list1 < list2 is

a) True

b) False

c) Error

d) None


Answer: b

Explanation: Elements are compared one by one.


15. To add a new element to a list, which command we have to use?

a) list1.add(5)

b) list1.append(5)

c) list1.addLast(5)

d) list1.addEnd(5)


Answer: b

Explanation: We use the function append() function, to add an element to the list.


16. To insert 5 to the third position in list1, which command do we have to use?

a) list1.add(3, 5)

b) list1.insert(2, 5)

c) list1.insert(3, 5)

d)  list1.append(3, 5)


Answer: c

Explanation: Execute in the shell to verify.


17. To remove the string “hello” from list1, which command do we have to use?

a) list1.remove(hello) 

b)  list1.remove(“hello”)

c) list1.removeAll(“hello”)

d) list1.removeOne(“hello”)


Answer: b

Explanation:  hello is a variable, "hello" is a string, we have to remove the string, so we have to              give the element as a string


18. Suppose list1 is [3, 4, 5, 20, 5], what is list1.index(5)?

a) 0

b) -1

c) 4

d) 2


Answer: d

Explanation: By default, the index is always considered from the left-hand side (0).


19. Suppose list_1 is [3, 4, 5, [5, 20, 15, 5],  5, 25, 1, 3], what is list_1.count(5)?

a) 4

b) 6

c) 1

d) 2


Answer: d

Explanation: Execute in the shell to verify.


20. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.reverse()?

a) [3, 4, 5, 20, 5, 25, 1, 3]

b) [1, 3, 3, 4, 5, 5, 20, 25]

c) [3, 1, 25, 5, 20, 5, 4, 3] 

d) [25, 20, 5, 5, 4, 3, 3, 1]


Answer: c

Explanation: Execute in the shell to verify.


21. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.extend([34, 5])?

a) [3,  4,  5,  20,  5,  25,  1,  3, [ 34, 5]]

b) [3,  4,  5,  20,  5,  25,  1,  3,  34,  5]

c) [25,  20,  5,  5,  4,  3,  3,  1,  34,  5]

d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]


Answer: b

Explanation: Execute in the shell to verify.

22. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is listExample after listExample.pop()?

a) [3, 4, 5, 20, 5, 25, 1]

b) [1, 3, 3, 4, 5, 5, 20, 25]

c) [3, 5, 20, 5, 25, 1, 3]

d) [1, 3, 4, 5, 20, 5, 25]


Answer: a

Explanation: pop() function will remove the last element in the list.


23. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after listExample.pop(1)?

a) [3, 4, 5, 20, 5, 25, 1, 3]

b) [1, 3, 3, 4, 5, 5, 20, 25]

c) [3, 5, 20, 5, 25, 1, 3]

d) [1, 3, 4, 5, 20, 5, 25]


Answer: c

Explanation: Generally pop() function will remove the last element in the list. 

        But inside the pop() function, if you provide an index then it will remove based on that index.


24. What will be the output of the following Python code?

>>>"Welcome to Python".split()

a)  (“Welcome”, “to”, “Python”)

b)  [“Welcome”, “to”, “Python”]

c) {“Welcome”, “to”, “Python”}

d) “Welcome”, “to”, “Python”


Answer: b

Explanation: split() function returns the elements in a list.


25. What will be the output of the following Python code?

>>>list_1 = [1, 3]

>>>list_2 = list_1

>>>list_1[0] = 4

>>>print(list_2)

a) [1, 3]

b) [4, 3]

c) [1, 4]

d) [1, 3, 4]


Answer: b

Explanation:  list_1 and list_2 are using the same memory location reason: Shallow copy

        if you change in list_1 it will affect list_2 vice versa       reason: Shallow copy 


26. What will be the output of the following Python code?

numbers = [1, 2, 3, 4]

numbers.append([5,6,7,8])

 print(len(numbers))

a) 4

b) 5

c) 8

d) 12


Answer: b

Explanation: A list is passed in append().

            append() function considers the entire list as a single element so the length is 5.


27. To which of the following the “in” operator can be used to check if an item is in it?

a) Lists

b) Dictionary

c) Set

d) All of the mentioned


Answer: d

Explanation: membership operator (in) can be used in all data structures (Datatypes).


28. What will be the output of the following Python code?

list1 = [1, 2, 3, 4]

list2 = [5, 6, 7, 8]

print(len(list1 + list2))

a) 2

b) 4

c) 5

d) 8


Answer: d

Explanation: + appends all the elements individually into a new list.

 

29. What will be the output of the following Python code?

veggies = ['carrot', 'drumsticks', 'potato', 'asparagus']

veggies.insert(veggies.index('drumsticks'), 'ladyfinger')

print(veggies)

a) [‘carrot’, ‘ladyfinger’, ‘potato’, ‘asparagus’]

b)  [‘carrot’, ‘ladyfinger’, 'drumsticks', 'potato', 'asparagus'] 

c) [‘carrot’, ‘drumsticks’, ‘ladyfinger’, ‘potato’, ‘asparagus’]

d) [‘ladyfinger’, ‘carrot’, ‘drumsticks’, ‘potato’, ‘asparagus’]


Answer: b

Explanation: Execute in the shell to verify.


30. What will be the output of the following Python code?

data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

 print(data[1][1][0])

a) 1

b) 2

c) 7

d) 5


Answer: C

Explanation: Execute in the shell to verify.


31. What will be the output of the following Python code?

points = [[1, 2], [3, 1.5], [0.5, 0.5]]

points.sort()

print(points)

a) [[1, 2], [3, 1.5], [0.5, 0.5]]

b) [[3, 1.5], [1, 2], [0.5, 0.5]]

c) [[0.5, 0.5], [1, 2], [3, 1.5]]

d) [[0.5, 0.5], [3, 1.5], [1, 2]]


Answer: c

Explanation: Execute in the shell to verify.


34. What will be the output of the following Python code?

s="a@b@c@d"

a=list(s.partition("@"))

print(a)

b=list(s.split("@"))

print(b)

a) [‘a’, ’b’, ’c’, ’d’]

[‘a’, ’b’, ’c’, ’d’]

b) [‘a’, ’@’, ’b’, ’@’, ’c’, ’@’, ’d’]

[‘a’, ’b’, ’c’, ’d’]

c) [‘a’,’@’,’b@c@d’]

[‘a’, ’b’, ’c’, ’d’]

d) [‘a’,’@’,’b@c@d’]

[‘a’, ’@’, ’b’, ’@’, ’c’, ’@’, ’d’]


Answer: c

Explanation: The partition function only splits for the first parameter along with 

the separator while the split function splits for the number of times given in the second argument but without the separator.



36. What will be the output of the following Python code?

a=[[]]*3

a[1].append(7)

print(a)

a) Syntax error

b) [[7], [7], [7]]

c) [[7], [], []]

d) [[],7, [], []]


Answer: b

Explanation: The first line of the code creates multiple reference copies of the sublist. [[], [], []] 

         Internally, the * operator uses a shallow copy (i.e., it uses the same memory location for all elements within the lists). 

when 7 is appended,  because of shallow copy, it gets appended to all the sublists.


38. What will be the output of the following Python code?

lst=[3,4,6,1,2]

lst[1:2]=[7,8]

print(lst)

a) [3, 7, 8, 6, 1, 2]

b) Syntax error

c) [3,[7,8],6,1,2]

d) [3,4,6,7,8]


Answer: a

Explanation: In the piece of code,  the slice assignment has been implemented. 

The sliced list is replaced by the assigned elements in the list. Type in Python shell to verify.


39. What will be the output of the following Python code?

a=[1,2,3]

b = a.append(4)

print(a)

print(b)

a) [1,2,3,4]

[1,2,3,4]

b) [1, 2, 3, 4]

None

c) Syntax error

d) [1,2,3]

[1,2,3,4]


Answer: b

Explanation: The append function on lists doesn’t return anything. Thus the value of b is None.

  

40. What will be the output of the following Python code?

>>> a = [14,52,7]

>>>> b = a.copy()  # deep copy

>>> b is a

         a) True

b) False


Answer: b

Explanation: here a data will be copied to b(deep copy) so it will create a separate memory location


41. What will be the output of the following Python code?

a=[13,56,17]

a.append([87])

a.extend([45,67])

print(a)

a) [13, 56, 17, [87], 45, 67]

b) [13, 56, 17, 87, 45, 67]

c) [13, 56, 17, 87,[ 45, 67]]

d) [13, 56, 17, [87], [45, 67]]


Answer: a

Explanation: The append function simply adds its arguments to the list as it is 

while extend function extends its arguments and later appends it.


42. What is the output of the following piece of code?

a=list((45,)*4)

print((45)*4)

print(a)

a) 180

[(45),(45),(45),(45)]

b) (45,45,45,45)

[45,45,45,45]

c) 180

[45,45,45,45]

d) Syntax error


Answer: c

Explanation: (45) is an int while (45,) is a tuple of one element. Thus, when a tuple is multiplied, 

It created references of itself, which are later converted into a list.


44. What will be the output of the following Python code?

word_1 = "Apple"

word_2 = "Apple"

list_1 = [1,2,3]

list_2 = [1,2,3]

print(word_1 is word_2)

print(list_1 is list_2)

a) True

True

b) False

True

c) False

False

d) True

False


Answer: d

Explanation: In the above case, both lists are equivalent but not identical as they have different objects.


45. What will be the output of the following Python code?

places = ['Bangalore', 'Mumbai', 'Delhi']

places1 = places      # shallow copy

        places1[1]="Pune"

places2 = places[ : ]   # deep copy

places2[2]="Hyderabad"

print(places)

a) [‘Bangalore’, ‘Pune’, ‘Hyderabad’]

b) [‘Bangalore’, ‘Pune’, ‘Delhi’]

c) [‘Bangalore’, ‘Mumbai’, ‘Delhi’]

d) [‘Bangalore’, ‘Mumbai’, ‘Hyderabad’]


Answer: b

Explanation: places1 is an alias for the list of places. Hence, any change made to places1 is reflected in places. 

places2 is a copy of the list of places. Thus, any change made to places2 isn’t reflected in places.


48. What will be the output of the following Python code?

a=["Apple","Ball","Cobra"]

a.sort(key = len)

print(a)

a) [‘Apple’, ‘Ball’, ‘Cobra’]

b) [‘Ball’, ‘Apple’, ‘Cobra’]

c) [‘Cobra’, ‘Apple’, ‘Ball’]

d) Invalid syntax for sort()


Answer: b

Explanation: The syntax isn’t invalid and the list is sorted according to the length of 

the strings in the list since the key is given as length.

Request: If you find this information useful, please provide your valuable comments.