Limited Deal
00d
00h
00m
00s

More from Learnfly

Python Interview Questions

Table Content Discuss Django architecture. How is memory managed in Python? How is NumpyArray better than a nested list? What is multithreading in Python? Are arguments passed i…

Team Learnfly
Super Editors
5 min read
Python Interview Questions
Table of contents

Python Interview Questions

Python is a popular programming language, developed by Guido Van Rossum in the late 1980s, and has since become an extremely popular language among software developers and data scientists, as it provides flexibility to incorporate dynamic semantics- the study of meaning in natural languages, that treated the meaning of sentences as a potential to be updated, as the context changes over time.

Python is an excellent language to start in the world of programming, known for its easy syntax, and popular for its simplicity and readability. Not only is the language’s versatility preferred by freshers, but experienced software developers also use this programming language to rapidly prototype and test their ideas. Python can be used for a wide range of applications, like web development, machine learning, data analysis, data science, and scientific computing. The active community of python contributes to the libraries and tools which has made it easier for contributors to add new functionality to python projects, without actually having to write code for themselves. Since Python is open source, anyone can contribute to the libraries, and at the same time, access the source code for themselves. There is a large community of programmers, always working to update information and improve programming and tools, adding to the efficiency and robustness of python.

Python developers are in high demand in every country, whose focus is on the technological advancement of the nation and its resources. Getting a job as a python developer is not a cakewalk, but remember, that there is a huge package of remuneration and bonus awaiting once you pass the assessment and crack job interviews. Here is our list of the top 15 python interview questions and answers:

Python Coding Questions:

  1. Discuss Django architecture.

This is a high-level python web framework, following the Model-Template-View architecture pattern, and is designed in such a way, that it separates the presentation layer, business logic layer, and database layer separately, making it easier to develop, maintain and scale applications. The models represent the data structure known as python classes and handle the data access, validation and relationships between the data. The templates are HTML files with replacements for data, reinstating actual data at runtime. Views in Django use logic for handling user requests and then retrieving and manipulating data, and using templates to provide results. Finally, the URLs in Django help to map the requested URL to the correct view and then pass the request to the view for processing. Thus, Django serves the page to the user.

  1. How is memory managed in Python?

Memory Management in Python is by Python Memory Manager, using a process known as reference counting, where the number of references to each object in the program is managed by the memory manager, which removes the memory of an object the moment its reference drops to zero. The garbage collector of the Python Memory Manager periodically disposes of objects that are no longer in use. Python has a dynamic system that increases and decreases memory and objects when it deems right to it.

  1. How is NumpyArray better than a nested list?

Numpy is coded in C and is backed by a simple-to-use model, while lists are typed, due to which Python needs to check the data type each time, before using it. As Numpy is coded in C, they are faster for mathematical operations, using a contiguous block of memory to store data. Lists on the other hand require more memory overhead. You can perform operations of different sizes and shapes on Numpy, which is called broadcasting. Moreover, NumPy arrays have many in-built functions to carry out statistical and mathematical operations.

  1. What is multithreading in Python?

This is the ability of python to run multiple threads simultaneously. Python Global Interpreter Lock doesn't permit running more than one smaller unit of a process, but multithreading permits concurrent execution of tasks within a single process, improving the performance and responsiveness of an application by using multiple CPU cores.

  1. Are arguments passed in Python by value or reference?

Arguments are passed in Python by reference, that is any changes made in the function can be seen in the original object. When you are passing an object to a function, the function receives the reference of the object, and therefore, any changes made inside the function affect the original object due to a shared memory location.

  1. How to generate random numbers in Python?

You need to import numbers by using the random module.

  1. If you are generating a random floating point between 0 and 1, the code is:

import random

random.random()

  1. If you are generating integer between two values, the code is:

import random

random.randint(a, b)

  1. If you want to generate a number from continuous values:

import random

random.uniform(a, b)

  1. What is the purpose of the pass statement?

When you require a code syntactically but don't want to execute a code, you use pass statement, which acts as a placeholder statement, with no actuall additional value. For example you write the code in the following way if you want to avoid a ‘syntaxerror’ in an ‘if’ clause: if True:

pass
def my_function(): pass
class MyClass: pass

  1. Is Python object-oriented or functional programming?

Python supports both object-oriented programming as well as functional programming styles. Object oriented you create classes of objects having similar behaviour, and then you create instances in these classes, by coding. In functional programming, you formulate functions to carry out specific tasks and avoid changing state and mutable data. Python’s design supports code readability over enforcing strict paradigms.

  1. How do you get indices of N maximum values in a NumPy array?

You can use ‘argpartition’ function from NumPy, which allows the rearrangement of elements in the input array, along the specified axis, so that the objects with ‘x’ largest value will occur at the first ‘x’ indices. Here is an example:

import numpy as np

a = np.array([3, 1, 9, 5, 2, 8])
n = 2
indices = np.argpartition(a, -n)[-n:]
print(indices)

Which will return the indices of the largest values in the array:
[2 5]

After which indices can be used to corresponding values in the actual array.

  1. How do you create a series from a List, NumPy array, and dictionary?

From a list:
import pandas as pd

data = [1, 2, 3, 4, 5]
s = pd.Series(data)

From a NumPy array:
import numpy as np
import pandas as pd

data = np.array([1, 2, 3, 4, 5])
s = pd.Series(data)

From a dictionary:
import pandas as pd

data = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
s = pd.Series(data)

The series ‘s’ has the same value as the real data.

  1. How to not have common items in Series A and Series B?

Use the ‘isin’ method and the logical ‘~’ operator:
import pandas as pd

series_a = pd.Series([1, 2, 3, 4, 5])
series_b = pd.Series([3, 4, 5, 6, 7])

non_common_elements = series_a[~series_a.isin(series_b)]

This will return the elements which are not common in both series.

  1. How do you keep only the top 2 most frequent values, and replace every other entry as ‘other’ in a series?

Replace using the ‘value_counts’ and ‘np.where’ functions. The code is”

import pandas as pd
import numpy as np

s = pd.Series([1, 2, 2, 3, 3, 3, 4, 5, 5, 6, 6, 6, 6])

top_2_values = s.value_counts().index[:2]
s = np.where(s.isin(top_2_values), s, 'other')

  1. How do you compute the Euclidean distance between two series?

The Euclidean distance can be completed using the ‘numpy’ library.
import numpy as np

series1 = pd.Series([1, 2, 3])
series2 = pd.Series([4, 5, 6])

distance = np.linalg.norm(series1 - series2)

The line np.linalg.norm calculates L-2 norm, which is the square root of the sum of the squares of the elements in a vector.

  1. How do you reverse the rows of a data frame in Python?

You can use the ‘.iloc’ accessor and slice with a negative step. For example, the following code will create a new frame with reversed rows.

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

df = df.iloc[::-1]

  1. How to use the slicing operator in Python?

The slicing operator appears like [:] to extract a portion of sequence, like a string, list or tuple, and the syntax is ‘sequence[start:stop:step]’. Here is an example of using slicing operator in Python:

>>> my_string = "Hello, World!"
>>> my_string[7:12]
'World'

>>> my_list = [1, 2, 3, 4, 5]
>>> my_list[1:4]
[2, 3, 4]

>>> my_tuple = (1, 2, 3, 4, 5)
>>> my_tuple[::2]
(1, 3, 5)

Learnfly offers professional courses on learning to code in Python programming language, building consolidated foundation, and interactive sessions with professionals in the field. Enrol early and get your hands on the quality sessions and courses for beginners.

Share
Written by
Team Learnfly

Super Editors

Learnfly Newsletter

Get the best of the Learnfly Blog

One short email each Friday — new articles, career tips, and the courses worth your time.