Python Interview Questions and Answers Set 6

51. Why is not all memory freed when python exits?

Objects referenced from the global namespaces of Python modules are not always de­allocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free (e.g. a tool like the one Purify will complain about these). Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object. If you want to force Python to delete certain things on de­allocation, you can use the at exit module to register one or more exit functions to handle those deletions.

52. What is Java implementation of Python popularly know?


53. What is used to create unicode strings in Python?

Add u before the string u ‘mystring’

54. What is a docstring?

docstring is the documentation string for a function. It can be accessed by function_name.__doc__

55. Given the list below remove the repetition of an element.

words =[‘one’,’one’,’two’,’three’,’three’,’two’]

A bad solution would be to iterate over the list and checking for copies somehow and then remove them!

A very good solution would be to use the set type. In a Python set, duplicates are not allowed.

So, list (set (words)) would remove the duplicates.

56. Print the length of each line in the file ‘file.txt’ not including any whitespaces at the end of the lines?



rstrip() is an inbuilt function which strips the string from the right end of spaces or tabs (whitespace characters).

57. What is wrong with the code?

func([1,2,3])# explicitly passing in a list

func() # using a default empty list

deffunc(n =[]) #do something with n

print n

This would result in a NameError. The variable n is local to function func and can’t be accessesd outside. So, printing it won’t be possible.

58. What does the below mean?

s = a + ‘[‘ + b + ‘:’ + c + ‘]’

Seems like a string is being concatenated. Nothing much can be said without knowing types of variables a, b, c. Also, if all of the a, b, c are not of type string, TypeError would be raised. This is because of the string constants (‘[‘ , ‘]’) used in the statement.

59. What are Python decorators?

A Python decorator is a specific change that we make in Python syntax to alter functions easily

60. What is namespace in Python?

In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.