We have compiled a list of top Python interview questions which are classified into 4 sections, namely:
List | Tuple |
---|---|
A list consists of mutable objects. (Objects which can be changed after creation) | A tuple consists of immutable objects. (Objects which cannot change after creation) |
List has a large memory. | Tuple has a small memory. |
List is stored in two blocks of memory (One is fixed sized and the other is variable sized for storing data) | Tuple is stored in a single block of memory. |
Creating a list is slower because two memory blocks need to be accessed. | Creating a tuple is faster than creating a list. |
An element in a list can be removed or replaced. | An element in a tuple cannot be removed or replaced. |
A list has data stored in [] brackets. For example, [1,2,3] | A tuple has data stored in () brackets. For example, (1,2,3) |
When to use each:
A tuple should be used whenever the user is aware of what is inserted in the tuple. Suppose that a college stores the information of its students in a data structure; in order for this information to remain immutable it should be stored in a tuple.
Since lists provide users with easier accessibility, they should be used whenever similar types of objects need to be stored. For instance, if a grocery needs to store all the dairy products in one field, it should use a list.
[snippet slug=python_basic_iq lang=abap]
All we have to do is create a tuple with three elements. The first element of the tuple is the first element of the list, which can be found using my_list[0]
.
The second element of the tuple is the last element in the list. my_list[len(my_list) - 1]
will give us this element. We could also have used the pop()
method, but that would alter the list.
List | Array |
---|---|
Python lists are very flexible and can hold arbitrary data. | Python arrays are just a thin wrapper on C arrays. |
Lists are a part of Python’s syntax, so they do not need to be declared first. | Arrays need to first be imported, or declared, from other libraries (i.e. numpy). |
Lists can also be re-sized quickly in a time-efficient manner. This is because Python initializes some extra elements in the list at initialization. | Arrays cannot be resized. Instead, an array’s values would need to be copied to another larger array. |
Lists can hold heterogeneous data. | Arrays can only store homogenous data. They have values with uniform data types. |
Mathematical functions cannot be directly applied to lists. Instead, they have to be individually applied to each element. | Arrays are specially optimized for arithmetic computations. |
Lists consume more memory as they are allocated a few extra elements to allow for quicker appending of items. | Since arrays stay the size that they were when they were first initialized, they are compact. |
A lambda function is a small anonymous function, which returns an object.
The object returned by lambda is usually assigned to a variable or used as a part of other bigger functions.
Instead of the conventional def keyword used for creating functions, a lambda function is defined by using the lambda
keyword.
The purpose of lambdas
A lambda is much more readable than a full function since it can be written in-line. Hence, it is a good practice to use lambdas when the function expression is small.
The beauty of lambda functions lies in the fact that they return function objects. This makes them helpful when used with functions like map
or filter
which require function objects as arguments.
Lambdas aren’t useful when the expression exceeds a single line.
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.
They are different types of inheritance supported by Python:
range()
and xrange()
For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use. The only difference is that range returns a Python list object and xrange returns an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators.
It is an environment variable, which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.
PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
In Python, iterators are used to iterate over a group of elements (in a list, for example). The way of implementing these iterators is known as generators. It yields an expression in the function, but otherwise behaves like a normal function.
__init__
is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__
method.
The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands.
Note: The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.
Syntax
The three operands in a ternary operator include:
true_val
: A value to be assigned if the expression is evaluated to true.false_val
: A value to be assigned if the expression is evaluated to false.var = true_val if condition else false_val
The variable var
on the left-hand side of the =
(assignment) operator will be assigned:
value1
if the booleanExpression evaluates to true
.value2
if the booleanExpression evaluates to false
.Example
[snippet slug=python_basic_iq1 lang=abap]
Explanation
The above code is using the ternary operator to find if a number is even or odd.
msg
will be assigned “even” if the condition (to_check % 2 == 0) is true
.msg
will be assigned “odd” if the condition (to_check % 2 == 0) is false
.Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows for polymorphism.
Global Variables:
Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
Local Variables:
Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
An exception is an error that occurs while the program is executing. When this error occurs, the program will stop and generate an exception which then gets handled in order to prevent the program from crashing.
The exceptions generated by a program are caught in the try
block and handled in the except
block.
Try
: Lets you test a block of code for errors.Except
: Lets you handle the error.The join
method in Python takes elements of an iterable data structure and connects them together using a particular string connector value.
How does join
work?
The join method in Python is a string method, which connects elements of a string iterable structure, which also contains strings or characters (array, list, etc.) by using a particular string as the connector.
Dictionary comprehension is one way to create a dictionary in Python. It creates a dictionary by merging two sets of data which are in the form of either lists or arrays.
The data of one of the two lists/arrays will act as the keys of the dictionary while the data of the second list/array will act as the values. Each key acts as a unique identifier for each value, hence the size of both lists/arrays should be the same.
In Python, the help() function is used for showing the documentation of modules, classes, functions, keywords, and so on. If the help() function receives no parameter, it launches an interactive help utility on the console.
The dir() function is used to return a valid list of attributes and methods of the object it is called upon. Since the function aims to produce the most relevant data (instead of showing the complete information), it behaves differently with different objects:
Python modules are files containing Python code that can be either function classes or variables. These modules are Python files having a .py extension. Modules can include a set of functions, classes, or variables that are both defined and implemented. You can import and initialize a module using the import statement, learning python tutorial will let us know more about python modules.
Here are some of the commonly used built-in modules in Python:
Benefits of modules in Python
There are a couple of key benefits of creating and using a module in Python:
In Python, “self” is a keyword used to define an instance or object of a class. Unlike in Java, where the self is optimal, in Python, it is primarily used as the first parameter. Self helps to distinguish between the methods and attributes of a class from its local variables.
The self variable in the __init__ method refers to the newly created object or instance, while in other methods, it pertains to the object or instance whose method was called.
It is one of the common questions in python interview questions and answers guide. Let’s see break, continue and pass in detail.
The break statement is used for terminating a loop when a specific condition is met, and the control is transferred to the following statement.
any()
and all()
?What is any()
?
any()
is a function that takes in an iterable (such as a list, tuple, set, etc.) and returns True
if any of the elements evaluate to True
, but it returns False
if all elements evaluate to False
.
Passing an iterable to any()
to check if any of the elements are True
.
one_truth = [True, False, False] three_lies = [0, '', None] print(any(one_truth)) print(any(three_lies))
The first print statement prints True
because one of the elements in one_truth
is True
.
On the other hand, the second print statement prints False
because none of the elements are True
, i.e., all elements are False
.
Use
any()
when you need to check a long series ofor
conditions.
What is all()
?
all()
is another Python function that takes in an iterable and returns True
if all of the elements evaluate to True
, but returns False
if otherwise.
Similar to any()
, all()
takes in a list, tuple, set, or any iterable.
all_true = [True, 1, 'a', object()] one_true = [True, False, False, 0] all_false = [None, '', False, 0] print(all(all_true)) print(all(one_true)) print(all(all_false))
The first function call returned True
because all_true
was filled with truthy values.
Passing one_true
to all()
returned False
because the list contained one or more falsy values.
Finally, passing all_false
to all()
returns False
because it also contained one or more falsy values.
Use
all()
when you need to check a long series ofand
conditions.
In Python, the assignment statement (= operator) does not copy objects, but instead, it creates a binding between the existing object and the target variable name. Thus, if you wish to create copies of an object in Python, you need to use the copy module. There are two ways to create copies for a particular object using the copy module:
Functions are a set of code used when we want to run the same method for more than 1 time.It reduces the length of program.Functions are defined into 2 categories –
1)function defination
2)function calling
Example
def dog():
print(“my name is tommy”)
dog();
string = "This is a string." string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘ print(string_list) #output: ['This', 'is', 'a', 'string.'] print(' '.join(string_list)) #output: This is a string.
*args
def multiply(a, b, *argv): mul = a * b for num in argv: mul *= num return mul print(multiply(1, 2, 3, 4, 5)) #output: 120
**kwargs
def tellArguments(**kwargs): for key, value in kwargs.items(): print(key + ": " + value) tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3") #output: # arg1: argument 1 # arg2: argument 2 # arg3: argument 3
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: