Intermediate Python Interview Questions Flashcards

1
Q

Explain split(), sub(), subn() methods of “re” module in Python?

A

These methods belong to the Python RegEx or ‘re’ module and are used to modify strings.

split(): This method is used to split a given string into a list.

sub(): This method is used to find a substring where a regex pattern matches, and then it replaces the matched substring with a different string.

subn(): This method is similar to the sub() method, but it returns the new string, along with the number of replacements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What do you mean by Python literals?

A

Generally, literals are a notation for representing a fixed value in source code. They can also be defined as raw values or data given in variables or constants. Python has different types of literal such as:

  1. String literals
  2. Numeric literals
  3. Boolean literals
  4. Literal Collections
  5. Special literals

Literals supported by python are listed below:

String Literals

These literals are formed by enclosing text in the single or double quotes.

For Example:

“Intellipaat”

‘45879’

Numeric Literals

Python numeric literals support three types of literals

Integer:I=10

Float: i=5.2

Complex:1.73j

Boolean Literals

Boolean literals help to denote boolean values. It contains either True or False.

x=True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a map function in Python?

A

The map() function in Python has two parameters, function and iterable. The map() function takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It returns an object list of results.

For example:

def calculateSq(n):

return n*n

numbers = (2, 3, 4, 5)

result = map( calculateSq, numbers)

print(result)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the generators in python?

A

Generator refers to the function that returns an iterable set of items.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are python iterators?

A

These are the certain objects that are easily traversed and iterated when needed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Do we need to declare variables with data types in Python?

A

No. Python is a dynamically typed language, I.E., Python Interpreter automatically identifies the data type of a variable based on the type of value assigned to the variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are Dict and List comprehensions?

A

Python comprehensions are like decorators, that help to build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or set. Comprehension saves a lot of time and code that might be considerably more complex and time-consuming.

Comprehensions are beneficial in the following scenarios:

  • Performing mathematical operations on the entire list
  • Performing conditional filtering operations on the entire list
  • Combining multiple lists into one
  • Flattening a multi-dimensional list

For example:

my_list = [2, 3, 5, 7, 11]

squared_list = [x**2 for x in my_list] # list comprehension

output => [4 , 9 , 25 , 49 , 121]

squared_dict = {x:x**2 for x in my_list} # dict comprehension

output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you write comments in python?

A

Comments in Python

Python Comments are the statement used by the programmer to increase the readability of the code. With the help of #, you can define the single comment and the other way to do commenting is to use the docstrings(strings enclosed within triple quotes).
For example:

print(“Comments in Python “)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Is multiple inheritance supported in Python?

A

Yes, unlike Java, Python provides users with a wide range of support in terms of inheritance and its usage. Multiple inheritance refers to a scenario where a class is instantiated from more than one individual parent class. This provides a lot of functionality and advantages to users.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the difference between range & xrange?

A

Functions in Python, range() and xrange() are used to iterate in a for loop for a fixed number of times. Functionality-wise, both these functions are the same. The difference comes when talking about Python version support for these functions and their return values.

RANGE() Method

  • In Python 3, xrange() is not supported; instead, the range() function is used to iterate in for loops
  • It returns a list
  • It takes more memory as it keeps the entire list of iterating numbers in memory

XRANGE() Method

  • The xrange() function is used in Python 2 to iterate in for loops
  • It returns a generator object as it doesn’t really generate a static list at the run time
  • It takes less memory as it keeps only one number at a time in memory
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is pickling and unpickling?

A

The Pickle module accepts the Python object and converts it into a string representation and stores it into a file by using the dump function. This process is called pickling. On the other hand, the process of retrieving the original Python objects from the string representation is called unpickling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What do you understand by Tkinter?

A

Tkinter is a built-in Python module that is used to create GUI applications. It is Python’s standard toolkit for GUI development. Tkinter comes with Python, so there is no separate installation needed. You can start using it by importing it in your script.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Is Python fully object oriented?

A

Python does follow an object-oriented programming paradigm and has all the basic OOPs concepts such as inheritance, polymorphism, and more, with the exception of access specifiers. Python doesn’t support strong encapsulation (adding a private keyword before data members). Although, it has a convention that can be used for data hiding, i.e., prefixing a data member with two underscores.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Differentiate between NumPy and SciPy?

A

NumPY

  • NumPy stands for Numerical Python
  • It is used for efficient and general numeric computations on numerical data saved in arrays. E.g., sorting, indexing, reshaping, and more
  • There are some linear algebraic functions available in this module, but they are not full-fledged

SciPy

  • SciPy stands for Scientific Python
  • This module is a collection of tools in Python used to perform operations such as integration, differentiation, and more
  • Full-fledged algebraic functions are available in SciPy for algebraic computations
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Explain all file processing modes supported in Python?

A

Python has various file processing modes.

For opening files, there are three modes:

  • read-only mode (r)
  • write-only mode (w)
  • read–write mode (rw)

For opening a text file using the above modes, we will have to append ‘t’ with them as follows:

  • read-only mode (rt)
  • write-only mode (wt)
  • read–write mode (rwt)

Similarly, a binary file can be opened by appending ‘b’ with them as follows:

  • read-only mode (rb)
  • write-only mode (wb)
  • read–write mode (rwb)

To append the content in the files, we can use the append mode (a):

  • For text files, the mode would be ‘at’
  • For binary files, it would be ‘ab’
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What do file-related modules in Python do? Can you name some file-related modules in Python?

A

Python comes with some file-related modules that have functions to manipulate text files and binary files in a file system. These modules can be used to create text or binary files, update their content, copy, delete, and more.

Some file-related modules are os, os.path, and shutil.os. The os.path module has functions to access the file system, while the shutil.os module can be used to copy or delete files.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Explain the use of the ‘with’ statement and its syntax?

A

In Python, using the ‘with’ statement, we can open a file and close it as soon as the block of code, where ‘with’ is used, exits. In this way, we can opt for not using the close() method.

with open(“filename”, “mode”) as file_var:

18
Q

Write a code to display the contents of a file in reverse?

A

To display the contents of a file in reverse, the following code can be used:

for line in reversed(list(open(filename.txt))):

print(line.rstrip())

19
Q

Which of the following is an invalid statement?

  1. xyz = 1,000,000
  2. x y z = 1000 2000 3000
  3. x,y,z = 1000, 2000, 3000
  4. x_y_z = 1,000,000
A

Ans. 2 statement is invalid.

20
Q

Write a command to open the file c:\hello.txt for writing?

A

Command:

f= open(“hello.txt”, “wt”)

21
Q

What does len() do?

A

len() is an inbuilt function used to calculate the length of sequences like list, python string, and array.

my _list=[1,2,3,4,5]

len(my_list)

22
Q

What does *args and **kwargs mean?

A
  • *args: It is used to pass multiple arguments in a function.
  • **kwargs: It is used to pass multiple keyworded arguments in a function in python.
23
Q

How will you remove duplicate elements from a list?

A

To remove duplicate elements from the list we use the set() function.

Consider the below example:

demo_list=[5,4,4,6,8,12,12,1,5]

unique_list = list(set(demo_list))

output:[1,5,6,8,12]

24
Q

How can files be deleted in Python?

A

You need to import the OS Module and use os.remove() function for deleting a file in python.
consider the code below:

import os

os.remove(“file_name.txt”)

25
Q

How will you read a random line in a file?

A

We can read a random line in a file using the random module.

For example:

import random

def read_random(fname):

lines = open(fname).read().splitlines()

return random.choice(lines)

print(read_random (‘hello.txt’))

26
Q

Write a Python program to count the total number of lines in a text file?

A

Method 1:

with open(r”myfile.txt”, ‘r’) as fp:

lines = len(fp.readlines())

print(‘Total Number of lines:’, lines)

Method 2:

with open(r”myfile.txt”, ‘r’) as fp:

for count, line in enumerate(fp):

pass

print(‘Total Number of lines:’, count + 1)

27
Q

What would be the output if I run the following code block?

A

list1 = [2, 33, 222, 14, 25]

print(list1[-2])

14

33

25

Error

Ans. output:14

28
Q

What is the purpose of is, not and in operators?

A

Operators are referred to as special functions that take one or more values(operands) and produce a corresponding result.

  • is: returns the true value when both the operands are true (Example: “x” is ‘x’)
  • not: returns the inverse of the boolean value based upon the operands (example:”1” returns “0” and vice-versa.
  • In: helps to check if the element is present in a given Sequence or not.
29
Q

Whenever Python exits, why isn’t all the memory de-allocated?

A
  • Whenever Python exits, 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 not possible to de-allocate those portions of memory that are reserved by the C library.
  • On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate every object.
30
Q

How can the ternary operators be used in python?

A

The ternary operator is the operator that is used to show conditional statements in Python. This consists of the boolean true or false values with a statement that has to be checked.

Syntax:

[on_true] if [expression] else [on_false]x, y = 10, 20 count = x if x < y else y

Explanation:

The above expression is evaluated like if x

31
Q

How to add values to a python array?

A

In python, adding elements in an array can be easily done with the help of extend(),append() and insert() functions.
Consider the following example:

x=arr.array(‘d’, [11.1 , 2.1 ,3.1] )

x.append(10.1)

print(x) #[11.1,2.1,3.1,10.1]

x.extend([8.3,1.3,5.3])

print(x) #[11.1,2.1,3.1,10.1,8.3,1.3,5.3]

x.insert(2,6.2)

print(x) # [11.1,2.1,6.2,3.1,10.1,8.3,1.3,5.3]

32
Q

How to remove values to a python array?

A

Elements can be removed from the python array using pop() or remove() methods.

pop(): This function will return the removed element .

remove():It will not return the removed element.

Consider the below example :

x=arr.array(‘d’, [8.1, 2.4, 6.8, 1.1, 7.7, 1.2, 3.6])

print(x.pop())

print(x.pop(3))

x.remove(8.1)

print(x)

Output:

  1. 6
  2. 1 # element popped at 3 rd index

array(‘d’, [2.4, 6.8, 7.7, 1.2])

33
Q

Write a code to sort a numerical list in Python?

A

The following code can be used to sort a numerical list in Python:

list = [“2”, “5”, “7”, “8”, “1”]

list = [int(i) for i in list]

list.sort()

print (list)

34
Q

Can you write an efficient code to count the number of capital letters in a file?

A

The normal solution for this problem statement would be as follows:

with open(SOME_LARGE_FILE) as countletter:

count = 0
text = countletter.read()
for character in text:
if character.isupper():
count += 1

To make this code more efficient, the whole code block can be converted into a one-liner code using the feature called generator expression. With this, the equivalent code line of the above code block would be as follows:

count sum(1 for line in countletter for character in line if character.isupper())

35
Q

How will you reverse a list in Python?

A

The function list.reverse() reverses the objects of a list.

36
Q

How will you remove the last object from a list in Python?

A

list.pop(obj=list[-1]):

Here, −1 represents the last element of the list. Hence, the pop() function removes the last object (obj) from the list.

37
Q

How can you generate random numbers in Python?

A

This achieved with importing the random module,it is the module that is used to generate random numbers.

Syntax:

import random

random.random # returns the floating point random number between the range of [0,1].

38
Q

How will you convert a string to all lowercase?

A

lower() function is used to convert a string to lowercase.

For Example:

demo_string=’ROSES’

print(demo_string.lower())

39
Q

Why would you use NumPy arrays instead of lists in Python?

A

NumPy arrays provide users with three main advantages as shown below:

  • NumPy arrays consume a lot less memory, thereby making the code more efficient.
  • NumPy arrays execute faster and do not add heavy processing to the runtime.
  • NumPy has a highly readable syntax, making it easy and convenient for programmers.
40
Q

What is Polymorphism in Python?

A

Polymorphism is the ability of the code to take multiple forms. Let’s say, if the parent class has a method named XYZ then the child class can also have a method with the same name XYZ having its own variables and parameters.

41
Q

Define encapsulation in Python?

A

encapsulation in Python refers to the process of wrapping up the variables and different functions into a single entity or capsule.Python class is the best example of encapsulation in python.

42
Q

What advantages do NumPy arrays offer over (nested) Python lists?

A

Nested Lists:

  • Python lists are efficient general-purpose containers that support efficient operations like insertion,appending,deletion and concatenation.
  • The limitations of lists are that they don’t support “vectorized” operations like element wise 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:

  • NumPy is more efficient and more convenient as you get a lot of vector and matrix operations for free, which helps to avoid unnecessary work and complexity of the code.Numpy is also efficiently implemented when compared to nested
  • NumPy array is faster and contains a lot of built-in functions which will help in FFTs, convolutions, fast searching, linear algebra,basic statistics, histograms,etc.