Advanced Python Interview Questions Flashcards
What is the lambda function in Python?
A lambda function is an anonymous function (a function that does not have a name) in Python. To define anonymous functions, we use the ‘lambda’ keyword instead of the ‘def’ keyword, hence the name ‘lambda function’. Lambda functions can have any number of arguments but only one statement.
For example:
l = lambda x,y : x*y
print(a(5, 6))
Output: 30
What is self in Python?
Self is an object or an instance of a class. This is explicitly included as the first parameter in Python. On the other hand, in Java it is optional. It helps differentiate between the methods and attributes of a class with local variables.
The self variable in the init method refers to the newly created object, while in other methods, it refers to the object whose method was called.
Syntax:
Class A:
def func(self):
print(“Hi”)
What is the difference between append() and extend() methods?
Both append() and extend() methods are methods used to add elements at the end of a list.
- append(element): Adds the given element at the end of the list that called this append() method
- extend(another-list): Adds the elements of another list at the end of the list that called this extend() method
How does Python Flask handle database requests?
Flask supports a database-powered application (RDBS). Such a system requires creating a schema, which needs piping the schema.sql file into the sqlite3 command. Python developers need to install the sqlite3 command to create or initiate the database in Flask.
Flask allows to request for a database in three ways:
- before_request(): They are called before a request and pass no arguments.
- after_request(): They are called after a request and pass the response that will be sent to the client.
- teardown_request(): They are called in a situation when an exception is raised and responses are not guaranteed. They are called after the response has been constructed. They are not allowed to modify the request, and their values are ignored.
What is docstring in Python?
Python lets users include a description (or quick notes) for their methods using documentation strings or docstrings. Docstrings are different from regular comments in Python as, rather than being completely ignored by the Python Interpreter like in the case of comments, these are defined within triple quotes.
Syntax:
””” Using docstring as a comment.
This code add two numbers “””
x=7
y=9
z=x+y
print(z)
How is Multithreading achieved in Python?
Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time.
- Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
- This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core.
What is slicing in Python?
Slicing is a process used to select a range of elements from sequence data type like list, string and tuple. Slicing is beneficial and easy to extract out the elements. It requires a : (colon) which separates the start index and end index of the field. All the data sequence types List or tuple allows us to use slicing to get the needed elements. Although we can get elements by specifying an index, we get only a single element whereas using slicing we can get a group or appropriate range of needed elements.
Syntax:
List_name[start:stop]
What is functional programming? Does Python follow a functional programming style? If yes, list a few methods to implement functionally oriented programming in Python.
Functional programming is a coding style where the main source of logic in a program comes from functions.
Incorporating functional programming in our codes means writing pure functions.
Pure functions are functions that cause little or no changes outside the scope of the function. These changes are referred to as side effects. To reduce side effects, pure functions are used, which makes the code easy-to-follow, test, or debug.
Python does follow a functional programming style. Following are some examples of functional programming in Python.
filter(): Filter lets us filter some values based on a conditional logic.
list(filter(lambda x:x>6,range(9))) [7, 8]
map(): Map applies a function to every element in an iterable. list(map(lambda x:x**2,range(5))) [0, 1, 4, 9, 16, 25]
reduce(): Reduce repeatedly reduces a sequence pair-wise until it reaches a single value.
from functools import reduce
reduce(lambda x,y:x-y,[1,2,3,4,5]) -13
Which one of the following is not the correct syntax for creating a set in Python?
- set([[1,2],[3,4],[4,5]])
- set([1,2,2,3,4,5])
- {1,2,3,4}
- set((1,2,3,4))
Ans. set([[1,2],[3,4],[4,5]])
Explanation: The argument given for the set must be iterable.
What is monkey patching in Python?
Monkey patching is the term used to denote the modifications that are done to a class or a module during the runtime. This can only be done as Python supports changes in the behavior of the program while being executed.
The following is an example, denoting monkey patching in Python:
monkeyy.py
class X:
def func(self):
print “func() is being called”
The above module (monkeyy) is used to change the behavior of a function at the runtime as shown below:
import monkeyy
def monkey_f(self):
print “monkey_f() is being called”
replacing address of “func” with “monkey_f”
monkeyy.X.func = monkey_f
obj = monk.X()
calling function “func” whose address got replaced
with function “monkey_f()”
obj.func()
What is the difference between / and // operator in Python?
- /: is a division operator and returns the Quotient value.
10/3
- 33
* // : is known as floor division operator and used to return only the value of quotient before decimal
10//3
3
What is pandas?
Pandas is an open source python library which supports data structures for data based operations associated with data analyzing and data Manipulation . Pandas with its rich sets of features fits in every role of data operation,whether it be related to implementing different algorithms or for solving complex business problems. Pandas helps to deal with a number of files in performing certain operations on the data stored by files.
What are dataframes?
A dataframe refers to a two dimensional mutable data structure or data aligned in the tabular form with labeled axes(rows and column).
Syntax:
pandas.DataFrame( data, index, columns, dtype)
data: It refers to various forms like ndarray, series, map, lists, dict, constants and can take other DataFrame as Input.
index: This argument is optional as the index for row labels will be automatically taken care of by pandas library.
columns: This argument is optional as the index for column labels will be automatically taken care of by pandas library.
Dtype: refers to the data type of each column.
How to combine dataframes in pandas?
The different dataframes can be easily combined with the help of functions listed below:
- Append():
This function is used for horizontal stacking of dataframes.
data_frame1.append(data_frame2)
-
concat(): This function is used for vertical stacking and best suites when the dataframes to be combined possess the same column and similar fields.
pd. concat([data_frame1, data_frame2]) - join(): This function is used to extract data from different dataframes which have one or more columns common.
data_frame1.join(data_frame2)
How do you identify missing values and deal with missing values in Dataframe?
Identification:
isnull() and isna() functions are used to identify the missing values in your data loaded into dataframe.
missing_count=data_frame1.isnull().sum()
Handling missing Values:
There are two ways of handling the missing values :
- Replace the missing values with 0
df[‘col_name’].fillna(0)
- Replace the missing values with the mean value of that column
df[‘col_name’] = df[‘col_name’].fillna((df[‘col_name’].mean()))