Tutorial Study Image

Python Interview Questions

List and Tuples are Built-in Data structures in python, that can hold multiple types of Data elements. whereas

  • Lists are Mutable, i.e they can be changed. But Tuples are Immutable.
  • Lists are slower compared to Tuples

The syntax for the List:

 list_1 = [10, ‘abc’, 11]

The syntax for a Tuple :

 tup_1 = (10, ‘abc’ , 11)
  1. Intrepreted language: Python does not need to be compiled before it is run.
  2. Dynamically typed: The variables are not needed to be declared before use.
  3. Supports object-orientated programming:  Allows the definition of Classes along with composition and inheritance.
  4. Free and opensource
  5. Portable: Code written in one operating system works in any other operating system6. 
  6. Supports other languages: Supports execution of code written in other programming languages such as Java, C, and C#.

Python is an Interpreted language used for General-purpose programming for backends. Python can also be used for Scripting, so it is also considered a Scripting Language.

Python code is not Compiled into Machine language instructions. It goes through an Interpreter, which turns your code into a Machine language and speeds up execution.

PEP stands for Python Enhancement Proposal. It is a set of rules, which help the programmers to code in a more human-readable format.

Pip is a package manager for python. It helps in installing additional packages and dependencies for running python programs.

In python, memory management is done as Python private heap space, managed by the Python memory manager, which makes object access fast. The garbage collector in python memory manager recycles the unused spaces and reassign pointers so that they can be used efficiently without memory holes.

A namespace is the set of all symbols used in python. These are kept similar to the dictionary to avoid naming conflicts.

PYTHONPATH is an environment variable. When a path is assigned to this variable, Python will look into the path for modules imported in the python program. Then If it is not found in this path interpreter raises an error.

The minimum requirement for a python module is that it should contain a python file. ie: file with '.py' extension. Additionally, it can be a folder containing any no of python files, including python classes, functions, etc. It can also have python executables.

Variables that are defined outside the scope of a function are called a Global variable. Whereas variables defined inside a function are called local variables, its scope is limited to that function only.

e.g., a = 'I am a global variable.'

def fun()

a = 'I am local to this function.'

print a ## Here, the value will be 'I am local to this function.'

print a ## Here, the value will be 'I am a global variable.'

Suppose a variable is assigned with some data, and the programmer wishes to change the type of the variable type conversion can be used.

eg : a = 1.0

b = int(a) // Here the 'a' was initially float, which is converted to int.

Similarly, the below-mentioned functions convert the type of python variables

float() – converts any data type into float type.

ord() – converts characters into an integer.

hex() – converts integers to hexadecimal.

oct() – converts an integer to octal.

tuple() – This function is used to convert to a tuple.

set() – This function returns the type after converting to set.

list() – This function is used to convert any data type to a list type.

dict() – This function is used to convert a tuple of order (key, value) into a dictionary.

str() – Used to convert an integer into a string.

complex(real,imag) – This function converts real numbers to complex(real,imag) numbers.

In python, code blocks are identified by the indentation. Loop structures, Classes, Functions, etc. are specified within an indented block. It is usually done using four space characters. If the code is not properly indented, the interpreter will throw an error.

Arrays and Lists are data structures in python that can hold more than one element. The difference is that Array can only store elements of the same data types, whereas lists can hold heterogeneous items, i.e., elements if different data types.

Note: In python, by default, an array data structure is not available, can be used by importing some modules like Numpy.

The Function is a block of code that gets executed to achieve a task when they are called. The concept of functions improves modularity and increases code reusability. The ?def? keywod is used to define functions Example: '?? Function Definition ??? def ExFun(): print("Hi,This is a function") ExFun(); #calling the function Output:Hi,This is a function

__init__ is a function/ method defined in every class. Whenever a new object is being created, this method will be called. They are also called Constructors.

Lambda functions or anonymous functions are single-line functions. These functions are defined without a name hence called Anonymous functions. The keyword lambda is used to define such functions.

Syntax : lambda arguments : expression Example: sum = lambda x,y : x+y print(sum(1, 2)) Output : 3

In python, there no default data structure Array. Arrays are accomplished using Lists. Numpy is a python library that provides faster Arrays. Numpy expands to Numerical Python.

Docstrings or documentation strings are used for associating documentation within code. Triple single quotes or triple-double quotes are used for docstrings. Comments in Python start with #.

Normally while calling functions, the values are used based on the positions. For example; def Subtract(a,b) return a-b While calling the function the parameter passed second will be subtracted first. But in keyword arguments, we can pass parameters in key = 'value' format. So that they will be used regardless of their positions. Example : Subtract(b=2,a=5) #result will be 3

Single Inheritance: Where a derived class acquires the members of a single superclass.

Multi-level inheritance: A derived class d1 is inherited from base class base1 and d2 inherited from d1.

Hierarchical inheritance: From one base class, we can inherit any number of child classes.

Multiple inheritance: A derived class, which is inherited from more than one base class.

Monkey patching in python means making modifications dynamically or at runtime. So that programs can be extended by changing only the running instance.

The word polymorphism means to exist in several forms. In python, polymorphism is the existence of functions with the same name used for different purposes.

We can achieve it by making changes in signatures. Which means, either the number of arguments or type of arguments will be changed. Polymorphism can also be seen in 'in-class' methods. The same-named methods can exist in different classes.

Abstraction is the process of hiding the implementation details from the user and emphasizing only on how to use the application. In python, data abstraction is achieved by using abstract classes and methods.

Encapsulation is the process of binding together data and methods to a single unit. In python, the concept of encapsulation is attained by the concept of classes. Classes act as a template of variables and methods together.

  • Class
  • Objects
  • Inheritance
  • Encapsulation
  • Data abstraction
  • Polymorphism

are the object oriented concepts that can be attained using python.

Django, Flask, and pyramid are full-stack frameworks based in python. These frameworks help developers to have clean web development.

The 'is' is a binary operator, it is used to check whether two variables point to the same object. It is usually used in checking the type of a variable.

Example:

a=1
if type(a) is int: 
   print(‘Yes’)
else: 
   print(‘No’)

The '==' operator checks whether the value of the two variables are equal or not.

The 'is' operator evaluates to true only if both the variable points to the same object. Even if the values are the same, the 'is' operator returns false if both variables point to different objects.

Membership operators are applied over sequences like Tuples, Strings, or Lists. There are two membership operators in python, 'in' and 'not in.'

The 'in' evaluates to True if the field element is found in the mentioned sequence. The 'not in' evaluates to True if the specified element is not found in the mentioned sequence.

For Example:

list_a = [1,2,3,4,5]
X= 5
Y= 10
if X in list_a:
     print(“Element Found)
else:
     print(“Element not Found)
If Y not in list_a:
     print(“This illustrates the not in membership”)

Output:
Element Found
This illustrates the not in membership

To access directories and files in python, one can use the operating system(os) module. The os module has a lot of functions to manipulate directories and files.

  1. os.getcwd(): Returns the current directory.
  2. os.chdr(path): It helps to change the directory to a specified path.
  3. os.listdir(): Lists the contents of the directory.
  4. os.makedir(): Creates a new directory.
  5. os.remove(file): Removes a file and raises an os exception if the specified file is not found

SciPy library which makes use of the NumPy module's array and helps the users to attain scientific programming. It helps in solving linear algebraic problems, calculus, etc.

Converting Python objects to a byte into byte streams is called pickling. This can be achieved using the pickle library in python.

Decorators are special functions in python, which modifies existing functions in python. Example:

def decorate_funs(fun):
    def inner_func():
        print("Now it is decorated\n")
        func()
    return inner


def exisitng_fun():
    print("I am an exisiting function")

>> existing_fun()
Returns “I am an exisitng function”
>>decorate_funs(exisitng_fun)
Returns :
Now it is decorated. 
“I am an existing function

Can also be written as:

@decorate_funs
def existing_fun():
    print("“I am an exisitng function")

Here decorate_funs is a decorator function which takes another function as parameter and makes changes to it.

No, In python, there no default data structure array. Arrays are accomplished using Lists. Numpy is a python library which provides faster arrays. Numpy expands to Numerical Python.

In python, there no default data structure array. Arrays are accomplished using lists. Numpy is a python library that provides faster arrays. Numpy expands to Numerical Python. Example:

import numpy as np
arr_eg = np.array([1, 2, 3, 4, 5])
print(arr_eg )

A set is a mutable data type with non-duplicate, unordered values, helps in attaining mathematical set like properties. Example: vehicle_set = { ‘car’, ’jeep’, ’bus’ }

A set is a mutable data type with non-duplicate, unordered values, helps in attaining mathematical set like properties Example: vehicle_set = {?car?,?jeep?,?bus?}

The add () method is used when only a single item is to be added to a set if more than one item to be added to a set the update() method is used. Example :

#add() method
vehicle_set = {‘car’,’jeep’,’bus’}
vehicle_set.add(‘van’)

#update() method
vehicle_set = {‘car’,’jeep’,’bus’}
vehicle_set.update([‘van’,’scooter’])

Both remove and discard methods will remove the specified item from a set. The difference is that if the specified item is not present in the set remove() method will raise an error but discard() will not. Example:

vehicle_set = {'car','jeep','bus'}
vehicle_set.remove('car')   #Removes 'car' from the set, if 'car' not found throws error.
vehicle_set.remove('bus')   #Removes 'bus' from set , no error will be thrown if 'bus' not found in the set.

All items in a set can be removed by the clear() method. Example:

vehicle_set = {‘car’,’jeep’,’bus’}
vehicle_set.clear()
print(vehicle_set)
## prints an empty set.

Dictionary is a collection of items saved in key, value pairs. They are mutable, indexed, and unordered. The values can be accessed using related keys. Example:

marks_dict = { 'physics' : 80 , 'chemistry' : 90, 'maths' : 95}

We can get only the values of a dictionary by using values() method Example:

marks_dict = { 'physics' : 80 , 'chemistry' : 90, 'maths' : 95}
marks_dict.values()

The keys() function can be used to return all keys of a dictionary as list. Example:

marks_dict = { ‘physics’ : 80 , ‘chemistry’ : 90, ‘maths’ : 95}
print(marks_dict.keys())

Output : [‘physics’,’chemistry’,’maths’]

The items() methods can be used to iterate over both keys and values. Example:

marks_dict = { ‘physics’ : 80 , ‘chemistry’ : 90, ‘maths’ : 95}

for sub,mark in  marks_dict.items():

     print(sub,mark)

This prints both keys and values.

import sys

print ("The python version in use is:", format(sys.version)).

Sys modules provide system-specific parameters and functions

Slicing is the process of taking a subset of some data. It is most commonly applied to Strings and Lists.

The 'in' keyword can be used to determine whether a key exists in a dictionary or not Example:

marks_dict = { ‘physics’ : 80 , ‘chemistry’ : 90, ‘maths’ : 95}
If ‘physics’ in marks_dict:
   print(‘yes’)

Output: yes

The slice() function is used to slice a part of a sequence like a String, Tuple, or List.

Syntax: slice(begin, end, step)

  • Begin: Index to begin slicing, by default 0
  • End: Index to end slicing
  • Step: How many steps to be taken for slicing, deafult is 1

The slice operator [n:m] returns the part of the string from the n'th character to the m'th character, including the first but excluding the last.

Output : [1,2,3,4,5,'a']

When we use the '=' operator to copy an object, a new object is not created, but a new variable is created, pointing to the old object. When we print( id(list1)) and print(id(list2)) we can see that both ids are the same.

One cannot create distinct copies of containers like a list using '=' in python. For creating a distinct copy one can use the copy module.

Copy module (Import Copy) provides deep copy and shallow copy. Shallow copy creates a new object by copying the old. But for nested items, it doesn't create new objects but uses the references.

So when we use shallow copy and if we change any existing element in the nested list the change will appear on both. Whereas in deep copy new objects will be created for nested objects too.

Copy module (Import Copy) provides deep copy and shallow copy. Shallow copy creates a new object by copying the old. But for nested items, it does not create new objects but use the references. So when we use shallow copy and if we change any existing element in the nested list the change will appear on both.

Whereas in deep copy new objects will be created for nested objects too. Example:

List_1 = [[1,1,1],[2,2,2],[3,3,3]]

List_2 = copy.copy(List_1) # Shallow Copy
List_1.append([4,4,4])
print(List2) # Output :  [[1,1,1],[2,2,2],[3,3,3]]

List_1[1][1] = ‘a’
print(List2) # Output :  [[1,1,1],[2,’a’,2],[3,3,3]]

Copy module (Import Copy) provides deep copy and shallow copy. Shallow copy creates a new object by copying the old. But for nested items, it does not create new objects but use the references. So when we use shallow copy and if we change any existing element in the nested list the change will appear on both.

Whereas in deep copy new objects will be created for nested objects too. Example:

List_1 = [[5,5,5],[6,6,6],[7,7,7]]

List_2 = copy.deepcopy(List_1) # Deep Copy
List_1.append([8,8,8])
print(List2) # Output :  [[5,5,5],[6,6,6],[7,7,7]]

List_1[1][1] = ‘a’
print(List1) # Output :  [[5,5,5],[6,’a’,6],[7,7,7],[8,8,8]
print(List2) # Output :  [[5,5,5],[6,6,6],[7,7,7]]

Self points to the current object of a class. Using the self, we can access the variables of the class and can apply member functions on the particular object

Lazy evaluation is a strategy used by an interpreter to reduce execution time and memory usage. In lazy evaluation, the result of an expression is not computed unless it is needed.

range() method uses the concept of lazy evaluation. For larger ranges, range will only provide the value when the value is used for execution.

A generator function is a normal function with a yield keyword inside it, taking the place of return. The yield keyword returns the value to the caller but saves state of the current function, too, to resume execution.

In short by using yields one can return value and continue executing the current callee.

If the programmer is not sure about the number of arguments to be passed to a function, the developer can put a '*' before the parameter name in the function definition.

The function will receive a tuple of arguments and the tuple can be of any length. The arguments can be passed as tuple elements and can be accessed accordingly.

If the programmer is not sure about the no of arguments to be passed to a function, the developer can put **( double asterisks )before the parameter name in the function definition.

The function will receive a dictionary of arguments, and the programmer can pass any no of arguments in key: value pairs and can access accordingly.

Functions can be written with the default value for parameters. If a function is written with default values for parameters, then even if no parameter value is passed to the function at the time of call, the function value will use the default value for computations. for Example:

def add( a, b =0)
     return a+b

add(2,3)  #returns 5
add(2)  #returns 2 

when 2 is passed the second parameter will be 0 since it is default value 2+0 = 0

Generally, empty code is not allowed inside functions, loops, class, if, etc. If the programmer wishes to add an empty code block, in such situations pass keyword can be used.

When the pass keyword is encountered by the interpreter, the interpreter does nothing but doesn't throw an error due to empty code. Example:

If (a > b): Pass

Recursion is a programming technique when a defined function can call itself repeatedly. Python supports recursion.

def find_factorial(n):
      if n==1:
           return n:
      Else:
           Return n*find_factorial(n-1) #The same function is called by itself.

An iterator is a sequence of items that can be traversed. Technically, an iterator object implements the iterator protocol, consist of the methods __iter__() and __next__().

When an iterable like a list is passed to the iter() method. The starting point is returned. Then using the next() method all items of the iterable can be accessed. Example:

List_1 = [1,2,3]
Iter = iter(List_1)
next(iter) # now points to 1 and returns 1
next(iter) # now points to 2 and returns 2 and so on

Lists, Tuples, Dictionaries, and Sets are all iterable objects.

All these objects have a iter() method which is used to get an iterator using the iter() method.

To make a class into an iterator, the developer has to implement __iter()__ and __next__() methods in the class.

The __iter()__ method can be used for operations but must return iterator object.

The __next()__ method can also be used for computations but should point to the next item.

When variables are declared inside a function, by default, they will have local scope only. That means they cannot be accessed outside the function.

To make such variables available in scope, we can append the global keyword before defining the variable.

JSON is a syntax for storing and exchanging data. In python, a built in module json is available to handle and manipulate 'json' data.

Python provides various standard exceptions to handle unexcepted errors and to debug the code efficiently. When an error occurs python stops and throws an error.

Try... Except is the standard method used for raising exceptions.

Syntax :

Try:
    Do something;
Except :
    Do somthing else
Finally:
   Do this finally

##finally is optional

Example:

    Try:
         4/0
    Except:
         print(‘Exception Occured”)

Sep and end parameters are used inside print. The end parameter takes a character and ends the statement printed with the specified parameter. Default the value for end is a new line.

Sep parameter helps the programmer to add separators between outputs. Example:

print(‘Hi Welcome’,end=’!’)
>> Hi Welcome!

Print(‘15’,’Aug’,’1947’,sep=’-’)
>>15-Aug-1947

Ternary operators are also called conditional operators. Ternary operators are used for evaluating anything based on binary True or False.

Syntax : [evaluate_on_true] if [expression] else [evaluate_on_false]

a if a > b else b

Any keyword can be used over an iterable, it is equivalent to successive OR operation. Returns true if any of the expressions in the iterable is true and returns false if all of the expressions are false or if the iterable is empty.

All keyword can be used over an iterable, it is equivalent to successive AND operation. Returns true if all of the expressions in the iterable is true and returns false if any of the expression is false.

In python comparisons can be chained, That means if two comparisons are to made, they can be combined as one For example: if x>y and y>z can be chained as if x> y >z.

The zip() method is mostly used as a looping technique. Zip helps to combine two similar iterables into one. Example:

ListA = [1,2,3]
ListB = ['a','b','c']

X = zip(ListA, ListB) 
print(X)

Output : [[1,'a'],[2,'b'],[3,'c']]

Identifiers can be formed using letters, numbers, and underscores. Reserved keywords cannot be used as identifiers. An identifier cannot be started with a number. The identifier can be of any length.

The assert keyword often finds its usage in debugging. Assert helps the programmer to check whether an expression returns True.

By using the assert keyword if a condition returns True nothing special happens, but if the given expression returns false, an Assertion Error is raised.

Syntax: assert condition

'//' is the operator for the truncation division. It is called so because it returns only the integer part of the Quotient, ignores the decimal part.

For example: 10//3 = 3.

  • '^': Operator represents the bitwise XOR operation.
  • '&': Bitwise AND.
  • '|': Bitwise OR.
  • '!': Represents bitwise NOT.
  • %s - String (or any object with a string representation, like numbers).
  • %d - Integers.
  • %f - Floating point numbers.
  • %<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
  • %x/%X - Integers in hex representation (lowercase/uppercase)

Both break and continue statements help in altering the flow of a loop.

The 'break' statement stops the flow and exits the loop.

The 'continue' statement stops the current iteration and continues with the next iteration if any.

The max() returns the character with the highest ASCII value.

Similarly min() function, when applied on a string, returns the character with minimum ASCII value.

'__add__' is a magic method that can be used for string concatenation.

Example : s1 = 'Python' s2 = 'programming' S1.__add(s2) Gives : Pythonprogramming

'__init__' is a function/ method defined in every class. Whenever a new object is being created, this method will be called. They are also called Constructors.

When the index is passed as a parameter, the __getitem_() function returns the character at the specified index

encode() method is used to encode strings in different formats. In python 3 the default string encoding is UTF8.

Syntax : string.encode(encoding='encode_format', error=error_response).
encoding_format for popular encoding like utf8, ASCII, etc.

Error response: What to be done on error.

  • Strict - is the default response that raises a Unicode Decode Error,
  • Replace - replace un encodable characters by ?,
  • Ignore - ignores unencodable characters.

We can use the function identifier() to check whether the selected identifier is valid or not in python.

split function splits a given string into a list of strings or characters. User can specify a delimiter based on which the splitting is done.

Syntax : String.split(delimiter, maxsplits).

Both the parameters are optional. If no delimiter is specified then the string gets split by space. Maxsplit specifies the maximum no of splits to bo performed. Example :

split_eg = ‘Mary had a little lamb’
split_list = split_eg.split()
Print(split_list)


Output : [‘Mary’,’had’,’a’,’little’,’lamb’]

The strip() function takes an argument and strips off the specified characters from the beginning and end of the string.

Syntax: string.strip(characters)

The characters parameter is optional if no character is provided the beginning and ending white spaces will be stripped off.

Example :

strip_eg = ‘   Hi    ‘
X = strip_eg.strip()
print(X) 


Output:Hi

The split function splits a given string into a list of strings or characters. Users can specify a delimiter based on which the splitting is done. If no delimiter is provided, the string will be split based on white spaces. Example:

split_eg = ‘Mary had a little lamb’
split_list = split_eg.split()
Print(split_list)

Output : [‘Mary’,’had’,’a’,’little’,’lamb’]

Splitlines() function splits the string in to list based on line breaks.
Syntax : string.splitlines(True/False).

If True is passed as a parameter the line break will be included in the resulting list, else the line break will be removed. The parameters are optional by default value is False.

example_str = ‘Mary had a little lamb\n its fleece are white as snow’
X = example_str.Splitlines(True)
print(X)

Output : [‘Mary had a little lamb\n’,’its fleece are white as snow’]

When the map function is used over a function and an iterable, the specified function will be executed for each item in iterable.

In other words, each item in the iterable will be passed as parameter to the function, and the function is executed.

Syntax : map(function,iterable)

Translate function is used to translate specified characters of a string to some other characters based on a mapping table.

To create this mapping table we can use maketrans() method. Example:

txt = ‘Smile Please’
mapping_table = txt.maketrans(‘a’,’@’)
print(txt.translate(mapping_table))

Output : Smile [email protected]

The translate function can work without the maketrans method. In such cases, we can use dictionaries as mapping tables. In such cases we have to use ASCII codes instead of characters Example:

txt = ‘Smile Please’
mapping_dict = {80:83}
Txt.translate(mapping_dict)

#returning string will have all ascii 80(P) replaced with ascii 83 (S)


Output : Smile Slease

The remove() function removes a specified item from the list, if more than one occurrence of the item is found, then removes the first occurrence.

Whereas pop() method takes an index as a parameter and pops out the item at that index and returns that item.

Syntax for remove() : string.remove(item)

Example for remove() : my_str = [1,2,3] my_str.remove(2)

Syntax for pop() : string.pop(index)

Example for pop() : my_str.pop(0) # returns 1

List Comprehension is a particular way supported by python which helps in creating and defining new lists from existing lists. Sometimes list comprehension replaces the use of loops.

Syntax : [Expression for element in list]

Example :

[item*2 for item in [1,2,3]]
Gives [2,4,6] 

The ‘+’ operator makes a new tuple by the concatenation of operands. 
Example : (‘a’, ‘b’ , ‘c’)  + (1,2,3)
Gives (‘a’, ‘b’,’c’, 1,2,3)

Frozen set means an immutable set. That means a set that cannot be changed. Frozenset() function can be used to make an immutable set from iterables like list, set, and dictionary.

Syntax : frozenset(iterable) # iterable is optional

Example :

Values = [1,2,3]
frozenset(Values)

Python supports the use of anonymous functions, they are functions without a name. These functions are defined using the lambda keyword.

Syntax: lambda arguments: expression

Example:sum = lambda x,y : x+y print(sum(1, 2)) Output : 3

When used inside a class, the functions are called methods. Methods are member functions pertaining to classes

Python supports the use of anonymous functions, they are functions without a name. These functions are defined using the lambda keyword.
Syntax: lambda arguments: expression

Example:

sum = lambda x,y : x+y
print(sum(1, 2))


Output : 3

'is ' and 'is not' are identity operators in python. 'Is' returns True if both operands point to the same object and false otherwise. 'is not' returns False if both operands point to the same object else returns False.

Dictionary will be returned by globals() and locals().

Locals() Returns a dictionary of variables defined in the local namespace.

Globals() Returns dictionary containing the global namespace of the module.

For processing and storing the categorical data in R we use the Factor data object.
 

The concept of Final was introduced in PHP version 5 and it indicates it is final. If it is a final class, it means it cannot be further extended. If the final was with the method then the method cannot be changed.
33. How can we pass the values through a URL or a form in PHP?
We can pass the values from the user into the PHP code from a URL by encrypting and decrypt using the function 
•    htmlspecialchars()
•    urlencode().