What are the basic questions asked in interview on python?
Introduction to Python:Python was developed by Guido van Rossum and was released first on February 20, 1991. It is one of the most widely-used and loved programming languages and is interpreted in nature thereby providing flexibility of incorporating dynamic semantics. It is also a free and open-source language with very simple and clean syntax. This makes it easy for developers to learn python. Python also supports object-oriented programming and is most commonly used to perform general-purpose programming. Show
Due to its simplistic nature and the ability to achieve multiple functionalities in fewer lines of code, python’s popularity is growing tremendously. Python is also used in Machine Learning, Artificial Intelligence, Web Development, Web Scraping, and various other domains due to its ability to support powerful computations using powerful libraries. Due to this, there is a huge demand for python developers in India and across the world. Companies are willing to offer amazing perks and benefits to these developers. In this article, we will see the most commonly asked python interview questions and answers which will help you excel and bag amazing job offers. We have classified them into the following sections:
Python Cheat Sheet: Basic to Advanced Concepts Python Interview Questions for Freshers1. What is Python? What are the benefits of using PythonPython is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, python supports objects, modules, threads, exception-handling, and automatic memory management which help in modelling real-world problems and building applications to solve these problems. Benefits of using Python:
2. What is a dynamically typed language?Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result. Type-checking can be done at two stages -
Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language. 3. What is an Interpreted language?An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step. 4. What is PEP 8 and why is it important?PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source community requires you to follow these style guidelines sincerely and strictly. 5. What is Scope in Python?Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows:
Note: Local scope objects can be synced with global scope objects using keywords such as global. 6. What are lists and tuples? What is the key difference between the two?Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets
7. What are the common built-in data types in Python?There are several built-in data types in Python. Although, Python doesn't require data types to be defined explicitly during variable declarations type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides
Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision.
Note: The standard library also includes additional types for processing:
A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary.
Note:
8. What is pass in Python?The
9. What are modules and packages in Python?Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages -
Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialized once
using the Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names. Note: You can technically import the package as well, but alas, it doesn't import the modules within the package to the local namespace, thus, it is practically useless. 10. What are global, protected and private attributes in Python?
11. What is the use of self in Python?Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python. 12. What is __init__?
13. What is break, continue and pass in Python?
14. What are unit tests in Python?
15. What is docstring in Python?
16. What is slicing in Python?
17. Explain how can you make a Python Script executable on Unix?
18. What is the difference between Python Arrays and lists?
Python Interview Questions for Experienced19. How is memory managed in Python?
20. What are Python namespaces? Why are they used?A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows:
The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects from an outer namespace. 21. What is Scope Resolution in Python?Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behavior are:
This behavior can be overridden using the
22. What are decorators in Python?Decorators
in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented the
The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function, i.e. 'wrapper' function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope.
23. What are Dict and List comprehensions?Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and code that might be considerably more verbose (containing more lines of code). Let's check out some examples, where comprehensions can be truly beneficial:
Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one.
A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements.
24. What is lambda in Python? Why is it used?Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways:
25. How do you copy an object in Python?In Python, the assignment statement ( Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the original object. If either of the values is a reference to other objects, just the reference addresses for the same are copied.
26. What is the difference between xrange and range in Python?xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static list, it creates the value on the go. This technique is commonly used with an object-type generator and has been termed as "yielding". Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a
Note: xrange has been deprecated as of Python 3.x. Now 27. What is pickling and unpickling?Python library offers a feature - serialization out of the box. Serializing an object refers to transforming it into a format that can be stored, so as to be able to deserialize it, later on, to obtain the original object. Here, the pickle module comes into play. Pickling:
Unpickling:
Note: Python has another, more primitive, serialization module called marshall, which exists primarily to support .pyc files in Python and differs significantly from the pickle. 28. What are generators in Python?Generators are functions that return an iterable collection of items, one at a time, in a set
manner. Generators, in general, are used to create iterators with a different approach. They employ the use of
29. What is PYTHONPATH in Python?PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location. 30. What is the use of help() and dir() functions?help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the
31. What is the difference between .py and .pyc files?
32. How Python is interpreted?
33. How are arguments passed by value or by reference in python?
In Python, arguments are passed by reference, i.e., reference to the actual object is passed.
34. What are iterators in Python?
35. Explain how to delete a file in Python?Use command os.remove(file_name)
36. Explain split() and join() functions in Python?
37. What does *args and **kwargs mean?*args
**kwargs
38. What are negative indexes and why are they used?
To create a class in python, we use the keyword “class” as shown in the example below:
To instantiate or create an object from the class created above, we do the following:
To access the name attribute, we just call the attribute using the dot operator as shown below:
To create methods inside the class, we include the methods under the scope of the class as shown below:
The self parameter in the init and introduce functions represent the reference to the current class instance which is used for accessing attributes and methods of that class. The self parameter has to be the first parameter of any method defined inside the class. The method of the class InterviewbitEmployee can be accessed as shown below:
The overall program would look like this:
40. How does inheritance work in python? Explain it with an example.Inheritance gives the power to a class to access all attributes and methods of another class. It aids in code reusability and helps the developer to maintain applications without redundant code. The class inheriting from another class is a child class or also called a derived class. The class from which a child class derives the members are called parent class or superclass. Python supports different kinds of inheritance, they are:
41. How do you access parent members in the child class?Following are the ways using which you can access parent class members within a child class:
42. Are access specifiers used in python?Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does not derive this from any variables. It has the concept of imitating the behaviour of variables by making use of a single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables without prefixed underscores are public. Example:
43. Is it possible to call parent class without its instance creation?Yes, it is possible if the base class is instantiated by other child classes or if the base class is a static method. 44. How is an empty class created in python?An empty class does not have any members defined in it. It is created by using the
pass keyword (the pass command does nothing in python). We can create objects for this class outside the class.
Output: 45. Differentiate between new and override modifiers.The new modifier is used to instruct the compiler to use the new implementation and not the base class function. The Override modifier is useful for overriding a base class function inside the child class. 46. Why is finalize used?Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps in performing memory management tasks. 47. What is init method in python?The init method
works similarly to the constructors in Java. The method is run as soon as an object is instantiated. It is useful for initializing any attributes or default behaviour of the object at the time of instantiation.
48. How will you check if a class is a child of another class?This is done by using a method called issubclass() provided by python.
The method tells us if any class is a child of another class by returning true or false accordingly.
Python Pandas Interview Questions49. What do you know about pandas?
50. Define pandas dataframe.A
dataframe is a 2D mutable and tabular structure for representing data labelled with axes - rows and columns.
where:
51. How will you combine different pandas dataframes?The dataframes can be combines using the below approaches:
52. Can you create a series from the dictionary object in pandas?One dimensional array capable of storing different data types is called a series. We can create pandas series from a dictionary object as shown below:
If an index is not specified in the input method, then the keys of the dictionaries are sorted in ascending order for constructing the index. In case the index is passed, then values of the index label will be extracted from the dictionary. 53. How will you identify and deal with missing values in a dataframe?We can identify if a dataframe has missing values by using the isnull() and isna() methods.
We can handle missing values by either replacing the values in the column with 0 as follows:
Or by replacing it with the mean value of the column
54. What do you understand by reindexing in pandas?Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If the values are missing in the previous index, then NaN/NA is placed in the location. A new object is returned unless a new index is produced that is equivalent to the current one. The copy value is set to False. This is also used for changing the index of rows and columns in the dataframe. 55. How to add new column to pandas dataframe?A new column can be added to a pandas dataframe as follows:
56. How will you delete indices, rows and columns from a dataframe?To delete an Index:
To delete row/column from dataframe:
57. Can you get items of series A that are not available in another series B?This can be achieved by using the
58. How will you get the items that are not common to both the given series A and B?We can achieve this by first performing the union of both series, then taking the intersection of both series. Then we follow the approach of getting items of union that are not there in the list of the intersection. The following code demonstrates this:
59. While importing data from different sources, can the pandas library recognize dates?Yes, they can, but with some bit of help. We need to add the parse_dates argument while we are reading data from the sources. Consider an example where we read data from a CSV file, we may encounter different date-time formats that are not readable by the pandas library. In this case, pandas provide flexibility to build our custom date parser with the help of lambda functions as shown below:
Numpy Interview Questions60. What do you understand by NumPy?NumPy is one of the most popular, easy-to-use, versatile, open-source, python-based, general-purpose package that is used for processing arrays. NumPy is short for NUMerical PYthon. This is very famous for its highly optimized tools that result in high performance and powerful N-Dimensional array processing feature that is designed explicitly to work on complex arrays. Due to its popularity and powerful performance and its flexibility to perform various operations like trigonometric operations, algebraic and statistical computations, it is most commonly used in performing scientific computations and various broadcasting functions. The following image shows the applications of NumPy: 61. How are NumPy arrays advantageous over python lists?
62. What are the steps to create 1D, 2D and 3D arrays?
63. You are given a numpy array and a new column as inputs. How will you delete the second column and replace the column with a new column value?Example:
New Column values:
Solution:
64. How will you efficiently load data from a text file?We can use the method
This method is highly efficient and even if this method feels less efficient, then the data should be represented in a more efficient format such as CSV etc. Various alternatives can be considered depending on the version of NumPy used. Following are the file formats that are supported:
65. How will you read CSV data into an array in NumPy?This can be achieved by using the genfromtxt() method by setting the delimiter as a comma.
66. How will you sort the array based on the Nth column?For example, consider an array arr.
Let us try to sort the rows by the 2nd column so that we get:
We can do this by using the sort() method in numpy as:
We can also perform sorting and that too inplace sorting by doing:
67. How will you find the nearest value in a given numpy array?We can use the argmin() method of numpy as shown below:
68. How will you reverse the numpy array using one line of code?This can be done as shown in the following:
where arr = original given array, reverse_array is the resultant after reversing all elements in the input. 69. How will you find the shape of any given NumPy array?We can use the shape attribute of the numpy array to find the shape. It returns the shape of the array in terms of row count and column count of the array.
Python Libraries Interview Questions70. Differentiate between a package and a module in python.The module is a single python file. A module can import other modules (other python files) as objects. Whereas, a package is the folder/directory where different sub-packages and the modules reside. A python module is created by saving a file with
the extension of A python package is created by following the below steps:
71. What are some of the most commonly used built-in modules in Python?Python modules are the files having python code which can be functions, variables or classes. These go by .py extension. The most commonly available built-in modules are:
72. What are lambda functions?Lambda functions are generally inline, anonymous functions represented by a single expression. They are used for creating function objects during runtime. They can accept any number of parameters. They are usually used where functions are required only for a short period. They can be used as:
73. How can you generate random numbers?Python provides a module called random using which we can generate random numbers.
74. Can you easily check if all characters in the given string is alphanumeric?This can be easily done by making use of the isalnum() method that returns true in case the string has only alphanumeric characters. For Example -
Another way is to use
75. What are the differences between pickling and unpickling?Pickling is the conversion of python objects to binary form. Whereas, unpickling is the conversion of binary form data to python objects. The pickled objects are used for storing in disks or external memory locations. Unpickled objects are used for getting the data back as python objects upon which processing can be done in python. Python provides a 76. Define GIL.GIL stands for Global Interpreter Lock. This is a mutex used for limiting access to python objects and aids in effective thread synchronization by avoiding deadlocks. GIL helps in achieving multitasking (and not parallel computing). The following diagram represents how GIL works. Based on the above diagram, there are three threads. First Thread acquires the GIL first and starts the I/O execution. When the I/O operations are done, thread 1 releases the acquired GIL which is then taken up by the second thread. The process repeats and the GIL are used by different threads alternatively until the threads have completed their execution. The threads not having the GIL lock goes into the waiting state and resumes execution only when it acquires the lock. 77. Define PYTHONPATH.It is an environment variable used for incorporating additional directories during the import of a module or a package. PYTHONPATH is used for checking if the imported packages or modules are available in the existing directories. Not just that, the interpreter uses this environment variable to identify which module needs to be loaded. 78. Define PIP.PIP stands for Python Installer Package. As the name indicates, it is used for installing different python modules. It is a command-line tool providing a seamless interface for installing different python modules. It searches over the internet for the package and installs them into the working directory without the need for any interaction with the user. The syntax for this is:
79. Are there any tools for identifying bugs and performing static analysis in python?Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively. PyChecker helps find bugs in python source code files and raises alerts for code issues and their complexity. Pylint checks for the module’s coding standards and supports different plugins to enable custom features to meet this requirement. 80. Differentiate between deep and shallow copies.
81. What is main function in python? How do you invoke it?In the world of programming
languages, the main is considered as an entry point of execution for a program. But in python, it is known that the interpreter serially interprets the file line-by-line. This means that python does not provide
Python Programming Examples82. Write python function which takes a variable number of arguments.A function that takes variable arguments is called a function prototype. Syntax:
For example:
The * in the function argument represents variable arguments in the function. 83. WAP (Write a program) which takes a sequence of numbers and check if all numbers are unique.You can do this by converting the list to set by using set() method and comparing the length of this set with the length of the original list. If found equal, return True.
84. Write a program for counting the number of every character of a given text file.The idea is to use collections and pprint module as shown below:
85. Write a program to check and return the pairs of a given array A whose sum value is equal to a target value N.This can be done easily by using the phenomenon of hashing. We can use a hash map to check for the current value of the array, x. If the map has the value of (N-x), then there is our pair.
86. Write a Program to add two integers >0 without using the plus operator.We can use bitwise operators to achieve this.
87. Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants:
By solving the equation, we get:
88. Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 'b’s.We can use the re module of python to perform regex pattern comparison here.
89. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.We can again use the re module to convert the date string as shown below:
You can also use the datetime module as shown below:
90. Write a Program to combine two different dictionaries. While combining, if you find the same keys, you can add the values of these same keys. Output the new dictionaryWe can use the Counter method from the collections module
91. How will you access the dataset of a publicly shared spreadsheet in CSV format stored in Google Drive?We can use the StringIO module from the io module to read from the Google Drive link and then we can use the pandas library using the obtained data source.
Conclusion:In this article, we have seen commonly asked interview questions for a python developer. These questions along with regular problem practice sessions will help you crack any python based interviews. Over the years, python has gained a lot of popularity amongst the developer’s community due to its simplicity and ability to support powerful computations. Due to this, the demand for good python developers is ever-growing. Nevertheless, to mention, the perks of being a python developer are really good. Along with theoretical knowledge in python, there is an emphasis on the ability to write good quality code as well. So, keep learning and keep practicing problems and without a doubt, you can crack any interviews. Important Resources:
Python MCQ
list1 = [3,4,5,2,1] list1 = [3,4,5,2,0] list1 = [3,5,2,1,0] list1 = [3,4,5,2] "Hello World" "World Hello" "dlroW olleH" "olleH dlroW" List is a sequence data type, while tuple is not. Tuples are mutable but lists are immutable. Tuple is a sequence data type, while lists is not. Lists are mutable but tuples are immutable. 100000000000000000000 1e+20 100000000000000000000.0 1.0e+20 __init__ is called manually on object creation. __init__ is a constructor method in Python. All classes have a __init__ method associated with them. __init__ allocates memory for objects. pickle.save() pickle.store() pickle.pickle() pickle.dump() __sara__ __ansh _sara_ ansh__ Python namespaces are implemented as a dictionary in Python. Python namespaces have keys as addresses of the objects. Lifecycle of a namespace depends upon the scope of the objects they are mapped to. Namespaces ensure that object names in a program are unique. ['s', 'a', 'r', 'a', 'a', 'n', 's', 'h'] ['s', 'r', 'a', 's', 'a', 'a', 'n', 'h'] ['sa', 'ra', 'an', 'sh'] ['sa', 'sa', 'sn', 'sh', 'ra', 'ra', 'rn', 'rh', 'aa', 'aa', 'an', 'ah', 'sa', 'sa', 'sn', 'sh'] Current time. Current time in milliseconds. Current time in milliseconds since midnight, January 1, 1970. Current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time). 4 8 24 4 4 64 4 8 64 None of the above (None, True, ‘IB007’) (‘Mr Employee’, True, ‘IB007’) (“”, False, ‘IB007’) Runtime error pd.read_csv(“sample_file.csv”, encoding=‘utf-8’) pd.read_csv(“sample_file.csv”, compression=‘gzip’) pd.read_csv(“sample_file.csv”, dialect=‘comma’) None of the above df.emptyframe df.blank df.isempty df.empty np.search(series_data % 5) np.find(series_data % 5 ==0) np.argwhere(series_data % 5==0) np.locate(series_data % 5) XYZ ABC XYZ PQR LMN ABC LMN PQR [num for num<0 in list] [num<0 in list] [num for num in list if num<0] [num in list for num<0] 5 Runtime error Duplicate Key Exception 3 How do I prepare for a Python programming interview?How to Stand Out in a Python Coding Interview. Select the Right Built-In Function for the Job. Iterate With enumerate() Instead of range() ... . Leverage Data Structures Effectively. Store Unique Values With Sets. ... . Take Advantage of Python's Standard Library. ... . Conclusion: Coding Interview Superpowers.. What is Python simple answer?Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. Python is a general-purpose language, meaning it can be used to create a variety of different programs and isn't specialized for any specific problems.
What are the coding questions in Python?Interview Questions for Python Coding. Question 3: Write a code snippet to reverse a string. ... . Question 4: Write a code snippet to sort a list in Python. ... . Question 5: What is the difference between mutable and immutable. ... . Question 6: How can you delete a file in Python. ... . Question 7: How to access an element of a list?. Is Python good for interview?There is no point in worrying about python being a good choice for coding interview. Your clarity of understanding the basics concepts of any programming language is very important. It doesn't matter whether you code in C,C++,Java, etc.
|