Top 15 Python Questions and Answers for Experienced

We’ve formulated this post to cover some of the trickiest Python questions and answers. Read all of them carefully to get familiar with the latest questions asked during Python interviews.

Also, please note that a good interviewer prepares himself before taking up any interview as per the job requirements. And most of the time, they will ask questions to evaluate your practical Python knowledge.

So apart from the core understanding of the subject, you should emphasize more on the application part to find the right edge in the interview. Don’t stick yourself to only reading books or watching online tutorials. Instead, read Python questions and answers directed towards interviews.

These efforts of yours will help you in getting the desired job profile of Python developer or a web development engineer working in Python Django.

💡 Fact – In Python, the statement “import this” prints the 19 verses of a poem known as Zen of Python.

Now, you can begin reading the questions/answers given in the below section. All of these are related to the application of Python and would test your scripting skills of the language.

Top 15 Python Questions and Answers for Experienced.

Top 15 Python Questions and Answers for Experienced

Python Questions and Answers for Experienced

💡 Fact – Python assumes a TAB equal to 8 Spaces.

Q-1. What is the function to randomize the items of a list in-place?

Ans. Python has a built-in module called as <random>. It exports a public method <shuffle(<list>)> which can randomize any input sequence.

import random
list = [2, 18, 8, 4]
print "Prior Shuffling - 0", list
print "After Shuffling - 1", list
print "After Shuffling - 2", list


Q-2. What is the best way to split a string in Python?

Ans. We can use Python <split()> function to break a string into substrings based on the defined separator. It returns the list of all words present in the input string.

test = "I am learning Python."
print test.split(" ")

Program Output.

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

['I', 'am', 'learning', 'Python.']


Q-3. What is the right way to transform a Python string into a list?

Ans. In Python, strings are just like lists. And it is easy to convert a string into the list. Simply by passing the string as an argument to the list would result in a string-to-list conversion.

list("I am learning Python.")

Program Output.

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

=> ['I', ' ', 'a', 'm', ' ', 'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g', ' ', 'P', 'y', 't', 'h', 'o', 'n', '.']


Q-4. How does exception handling in Python differ from Java? Also, list the optional clauses for a <try-except> block in Python?

Ans. Unlike Java, Python implements exception handling in a bit different way. It provides an option of using a <try-except> block where the programmer can see the error details without terminating the program. Sometimes, along with the problem, this <try-except> statement offers a solution to deal with the error.

There are following clauses available in Python language.

1. try-except-finally
2. try-except-else


Q-5. What do you know about the <list> and <dict> comprehensions? Explain with an example.

Ans. The <List/Dict> comprehensions provide an easier way to create the corresponding object using the existing iterable. As per official Python documents, the list comprehensions are usually faster than the standard loops. But it’s something that may change between releases.

The <List/Dict> Comprehensions Examples.

#Simple Iteration
item = []
for n in range(10):
print item


#List Comprehension

item = [n*2 for n in range(10)]
print item


Both the above example would yield the same output.

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


#Dict Comprehension
item = {n: n*2 for n in range(10)}
print item


Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}


💡 Fact – In interactive mode, the last printed expression is assigned to the variable _ (underscore).

Q-6. What are the methods you know to copy an object in Python?

Ans. Commonly, we use <copy.copy()> or <copy.deepcopy()> to perform copy operation on objects. Though not all objects support these methods but most do.

But some objects are easier to copy. Like the dictionary objects provide a <copy()> method.


item = {n: n*2 for n in range(10)}
newdict = item.copy()
print newdict


Q-7. Can you write code to determine the name of an object in Python?

Ans. No objects in Python have any associated names. So there is no way of getting the one for an object. The assignment is only the means of binding a name to the value. The name then can only refer to access the value. The most we can do is to find the reference name of the object.


class Test:
    def __init__(self, name): = [] = name

    def __str__(self):
        return '{} holds ...'.format(
obj1 = Test('obj1')
print obj1

obj2 = Test('obj2')
print obj2


Q-8. Can you write code to check whether the given object belongs to a class or its subclass?

Ans. Python has a built-in method to list the instances of an object that may consist of many classes. It returns in the form of a table containing tuples instead of the individual classes. Its syntax is as follows.

<isinstance(obj, (class1, class2, ...))>

The above method checks the presence of an object in one of the classes. The built-in types can also have many formats of the same function like <isinstance(obj, str)> or <isinstance(obj, (int, long, float, complex))>.

Also, it’s not recommended to use the built-in classes. Create an user-defined class instead.

We can take the following example to determine the object of a particular class.


def lookUp(obj):
    if isinstance(obj, Mailbox):
        print "Look for a mailbox"
    elif isinstance(obj, Document):
        print "Look for a document"
        print "Unidentified object"


Q-9. What is the result of the following Python program?

Ans. The example code is as follows.

def multiplexers ():

    return [lambda n: index * n for index in range (4)]

print [m (2) for m in multiplexers ()]


Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

[6, 6, 6, 6]


The output of the above code is <[6, 6, 6, 6]>. It’s because of the late binding as the value of the variable <index> gets looked up after a call to any of multiplexers functions.


Q-10. What is the result of the below lines of code?

Here is the example code.

def fast (items= []):
    items.append (1)
    return items

print fast ()
print fast ()

Ans. The above code will give the following result.

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

[1, 1]

The function <fast> evaluates its arguments only once after the function gets defined. However, since <items> is a list, so it’ll get modified by appending a <1> to it.

💡 Fact – You can inspect objects in Python by using dir().

Q-11. What is the result of the below Python code?

keyword = 'aeioubcdfg'
print keyword [:3] + keyword [3:]

Ans. The above code will produce the following result.


In Python, while performing string slicing, whenever the indices of both the slices collide, a <+> operator get applied to concatenates them.


Q-12. How would you produce a list with unique elements from a list with duplicate elements?

Ans. Iterating the list is not a desirable solution. The right answer should look like this.

duplicates = ['a','b','c','d','d','d','e','a','b','f','g','g','h']
uniqueItems = list(set(duplicates))
print sorted(uniqueItems)


Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


Q-13. Can you iterate over a list of words and use a dictionary to keep track of the frequency(count) of each word? Consider the below example.

{'Number':Frequency, '2':2, '3':2}

Ans. Please find out the below code.

def dic(words):
  wordList = {}
  for index in words:
      wordList[index] += 1
    except KeyError:
      wordList[index] = 1
  return wordList
print wordList

print dic(wordList)


Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux

['1', '3', '2', '4', '5', '3', '2', '1', '4', '3', '2']
{'1': 2, '3': 3, '2': 3, '5': 1, '4': 2}


Q-14. What is the result of the following Python code?

class Test(object):
    def __init__(self):
        self.x = 1
t = Test()
print t.x
print t.x
print t.x
print t.x

Ans. All print statement will display <1>. It’s because the value of object’s attribute(x) is never changing.

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux


Also, <x> becomes a part of the public members of class Test.

Hence, it can be accessed directly.


Q-15. Can you describe what’s wrong with the below code?

testProc([1, 2, 3]) # Explicitly passing in a list
testProc()  # Using a default empty list
def testProc(n = []):
    # Do something with n
print n

Ans. The above code would throw a <NameError>.

The variable n is local to the function <testProc> and can’t be accessed outside.

So, printing it won’t be possible.


Summary – Top 15 Python Questions and Answers for Experienced.

So it was one of the posts where we took up an essential topic for Software engineers. Also, Python programming is becoming more and more relevant for the automation testing. That’s why we came up with this blog post on the top Python questions and answers for experienced engineers.

It would be great if you let us know your feedback on this post.

Also, you can ask us to write on a topic of your choice. We’ll add it to our writing roadmap.

Lastly, if you’d enjoyed the post, then please care to share it with friends and on social media.

Keep Learning,