Python Certification is the most sought-after skill in programming domain. In this Python Interview Questions blog, I will introduce you to the most frequently asked questions in Python interviews. This blog is the perfect guide for you to learn all the concepts required to clear a Python interview. Our Python Interview Questions is the one-stop resource from where you can boost your interview preparation. We have 40 questions on Python Programming and additional 10 MCQs which will help you with different expertise levels to reap the maximum benefit from our blog.
So, if you are planning to start your career in Python and wish to know the skills related to it, now is the right time to dive in, when the technology is in its nascent state. If you have other doubts regarding Python, feel free to post them in our QnA Forum. Our expert team will get back to you at the earliest.
Q1. What is the difference between list and tuples?
Q2. What are the key features of Python?
Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.
Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++'s public, private), the justification for this point is given as "we are all adults here"
Python finds use in many spheres - web applications, automation, scientific modeling, big data applications and many more. It's also often used as "glue" code to get other languages and components to play nice.
Q3. What is the difference between deep and shallow copy?
A shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. A shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.
A deep copy is used to store the values that are already copied. Deep copy doesn't copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed out by some other object gets stored. The changes made in the original copy won't affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.
Q4. How is Multithreading achieved in Python?
Python has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it.
Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your â??threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.
All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn't a good idea.
Q5. How can the ternary operators be used in python?
The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.
The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.
Q6. How is memory managed in Python?
Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
The allocation of heap space for Python objects is done by Python's memory manager. The core API gives access to some tools for the programmer to code.
Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.
Q7. Explain Inheritance in Python with an example.
Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.
Single Inheritance: Where a derived class acquires the members of a single superclass.
Multi-level inheritance: A derived class d1 in inherited from base class base1, and d2 are inherited from base2.
Multiple inheritances: A derived class is inherited from more than one base class.
Q8. Explain what Flask is and its benefits?
Flask is a web microframework for Python based on "Werkzeug, Jinja2 and good intentions" BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs.
A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
Q9. What is the usage of help() and dir() function in Python?
Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
Dir() function: The dir() function is used to display the defined symbols.
Q10. Whenever Python exists, why isn't all the memory de-allocated?
Whenever Python exists, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed.
It is impossible to de-allocate those portions of memory that are reserved by the C library.
On exit, because of having its own efficient cleanup mechanism, Python would try to de-allocate/destroy every other object.
Q11. What is a dictionary in Python?
The built-in datatypes in Python are called a dictionary. It defines a one-to-one relationship between keys and values. Dictionaries contain a pair of keys and their corresponding values. Dictionaries are indexed by keys.
The following example contains some keys. A country, Capital & PM. Their corresponding values are India, Delhi, and Modi respectively.
Q12. What is monkey patching in Python?
In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
As we can see, we did make some changes in the behavior of f() in MyClass using the function we defined, monkey_f(), outside of the module m.
Q13. Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory?
Let us first write a multiple line solution and then convert it to one-liner code.
Q14. What are negative indexes and why are they used?
The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses â??0' that is used as the first index and â??1' as the second index and the process goes on like that.
The index for the negative number starts from â??-1' that represents the last index in the sequence and â??-2' as the penultimate index and the sequence carries forward like the positive number.
The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S=-1. The negative index is also used to show the index to represent the string in the correct order.
Q15. How can you randomize the items of a list in place in Python?
The output of the following code is as below.
Q16. What is the process of compilation and linking in python?
The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.
Place this file in the Modules/ directory of the distribution which is getting used.
Add a line in the file Setup.local that is present in the Modules/ directory.
After a successful run of this rebuild the interpreter by using the make command on the top-level directory.
If the file is changed then run rebuildMakefile by using the command as â??make Makefile'.
Q17. Write a sorting algorithm for a numerical dataset in Python.
Q18. Looking at the below code, write down the final values of A0, A1,...An.
Q19. Explain split(), sub(), sub n() methods of "re" module in Python.
split() â?? uses a regex pattern to "split" a given string into a list.
sub() â?? it is similar to the sub() and also returns the new string along with the no. of replacements.
Q20. What is the difference between the range & x range?
For the most part, x range and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an x range object.
This means that x range doesn't actually generate a static list at run-time as range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you'd like to generate a list for, say one billion, x range is the function to use.
This is especially true if you have a real memory sensitive system such as a cell phone that you are working with, as the range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It's a memory hungry beast.
Q21. What is pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
Q22. Mention the differences between Django, Pyramid, and Flask.
Flask is a "microframework" primarily build for a small application with simpler requirements. In a flask, you have to use external libraries. Flask is ready to use.
The pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. The pyramid is heavy configurable.
Django can also be used for larger applications just like Pyramid. It includes an ORM.
Q24. Explain how you can set up the Database in Django.
You can use the command edit my site/setting.py, it is a normal python module with module level representing Django settings.
Django uses SQLite by default; it is easy for Django users as such it won't require any other type of installation. In the case, your database choice is different that you have to the following keys in the DATABASE â??default' item to match your database connection settings.
Name The name of your database. In the case if you are using SQLite as your database, in that case, the database will be a file on your computer, Name should be a full absolute path, including the file name of that file.
If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.
Django uses SQLite as the default database, it stores data as a single file in the filesystem. If you do have a database serverâ??PostgreSQL, MySQL, Oracle, MSSQLâ??and want to use it rather than SQLite, then use your database's administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project's settings.py file comes in.
Q25. Give an example of how you can write a VIEW in Django?
Q26. Mention what the Django templates consist of.
The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that control the logic of the template.
Q27. Explain the use of session in Django framework?
Django provides a session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side and storing all the related data on the server side.
Q28. List out the inheritance styles in Django.
Abstract Base Classes: This style is used when you only want parent's class to hold information that you don't want to type out for each child model.
Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table.
Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model's fields.
Q29. What is map function in Python?
Map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.
Q30. What advantages do NumPy arrays offer over (nested) Python lists?
Python's lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python's list comprehensions make them easy to construct and manipulate.
They have certain limitations: they don't support "vectorized" operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element.
NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.
Q31. Explain the use of decorators.
Decorators in Python are used to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc.
Q32. What is the difference between NumPy and SciPy?
In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic elementwise functions, et cetera.
All numerical code would reside in SciPy. However, one of NumPy's important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors.
Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms.
If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.
Q33. How do you make 3D plots/visualizations using NumPy/SciPy?
Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.
Q34. Why are local variable names beginning with an underscore discouraged?
As Python has no concept of private variables, leading underscores are used to indicate variables that must not be accessed from outside the class.
Q35. Which of the following is an invalid statement?
Spaces are not allowed in variable names.
Q36. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?
The index -1 corresponds to the last index in the list.
Q37. When will the else part of try-except-else be executed?
The else part is executed when no exception occurs.
Q38. What is the maximum possible length of an identifier?
Identifiers can be of any length.
Q39. Which one of these is floor division?
Answer: b) The location contains double slashes ( \\ ) and w is used to indicate that file is being written to.