This article contains most common Python interview questions.
Question 1 : Explain best practices for using import in a module.
Answer: As a best practice we should not use from modulename import *
,
by having import like this makes it harder for linters to detect undefined names. Import modules at the top of
file.
Import the modules in the following order :
1. standard library modules – e.g. sys, os, re
2. third-party library modules (anything installed in Python’s site-packages directory) - e.g requests, pandas,
PIL
etc.
3. locally-developed modules
Question 2: Explain difference between arguments and parameters.
Answer : Parameters are defined by the names that appear in a function definition, whereas
arguments are the values
actually passed to a function when calling it. Parameters define what types of arguments a function can accept.
Lets
look in below example.
def func(foo, bar=None, **kwargs):
pass
foo, bar and kwargs are parameters of func.
However, when calling func, as shown below, the values test, 123, and dummy_value are arguments.
func(test, bar=123, extra=dummy_value)
Question 3: How we can find methods or attributes of an object in python?
Answer: By using dir
. dir(x)
returns an alphabetized list of the
names
containing the instance
attributes and
methods
and attributes defined by its class.Below is the example.
dummy_string = "Hello"
print(dir(dummy_string))
# Output
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
'center',
'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha',
'isascii',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
'join',
'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Question 4: Explain use of the slash(/) in the parameter list of a function.
Answer: A slash in the argument list of a function denotes that the parameters prior to it are
positional-only.
Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts
positional-only parameters, arguments are mapped to parameters based solely on their position. For example,
float()
is a
function that accepts positional-only parameters. Below is the documentation for float().
print(help(float))
Help on class float in module builtins:
class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating point number, if possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| self != 0
The slash at the end of the parameter list means that both parameters are positional-only. Thus, calling float()
with
keyword arguments would lead to an error.
print(float(x=7))
# Output
Traceback (most recent call last):
File "/home/gcptutorials/Desktop/post_temp/test.py", line 1, in
print(float(x=7))
TypeError: float() takes no keyword arguments
Question 5: Explain negative indexing in Python.
Answer : Python sequences are indexed with positive numbers and negative numbers. For positive
numbers 0 is the
first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the
penultimate
(next to last) index and so forth. Using negative indices can be very convenient. For example S[:-1] is all of
the
string except for its last character, which is useful for removing the trailing newline from a string.Refer
below
example.
test_string = "negative indexing example"
print(test_string[0])
print(test_string[-1])
print(test_string[:-1])
# Output
n
e
negative indexing exampl
Question 6: What are hashable objects in Python.
Answer: An object is hashable if it has a hash value which never changes during its
lifetime
(it needs a
__hash__()
method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare
equal
must have the same hash value.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use
the
hash
value internally.
Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries)
are
not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable.
Question 7: Explain difference between copy and deepcopy in Python.
Answer: copy(x) returns a shallow copy of x. deepcopy(x[, memo]) returns a deep copy of x. The
difference
between
shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists
or
class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to
the
objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found
in
the original.
Question 8: Explain difference between relative and absolute imports in Python.
Answer: Relative imports use leading dots. A single leading dot indicates a relative import,
starting with the
current package. Two or more leading dots indicate a relative import to the parent(s) of the current package,
one
level per dot after the first. For example, given the following package layout:
package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleY.py
subpackage2/
__init__.py
moduleZ.py
moduleA.py
In subpackage1/moduleX.py the following are valid relative imports:
from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
Absolute imports use either the import xyz or from xyz import abc syntax.
import re
import os
Question 9: Explain str.join method in Python.
Answer: str.join method returns a string which is the concatenation of the strings in iterable.
A TypeError will
be
raised if there are any non-string values in iterable, including bytes objects. The separator between elements
is
the string providing this method.
str_list = ["test", "string", "to", "join"]
print("-".join(str_list))
# Ouput
test-string-to-join
Error with non-string values in iterable
str_list = ["test", "string", "to", "join", 12]
print("-".join(str_list))
# Output
Traceback (most recent call last):
File "/home/gcptutorials/Desktop/post_temp/test.py", line 3, in
print("-".join(str_list))
TypeError: sequence item 4: expected str instance, int found
Question 10: What are Lambda Expressions in Python
Answer: With the Lambda Keyword small anonymous functions can be created. Lambda functions
can be used
wherever
function objects are required. They are syntactically restricted to a single expression.The below example
uses a
lambda expression to return a function.
def get_number_square(n):
return lambda x: x * x
func = get_number_square(5)
print(type(func))
print(func(5))
# Output
<class 'function'>
25
Category: Python