Python Interview Questions

Sep 18, 2022
100 views
24 questions

Python is one of the most popular and widely-used programming language developed by Guido van Rossum. The first version of Python programming language was released on February 20, 1991. Python is one of the trending programming language since its first release used for creating API, Web portals and automation of tasks. You are here to read best Python interview questions that written by our Experienced Python instructor for candidates who want to make their carrer as Python developer.

About Python

Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation.

Key Features of Python

  Expressive Syntax
  Cross-platform support
  Open Source and free to use
  Easily Extensible
  Easily integrated with other languages
  Interpreted Language
  Dynamically Typed
  Large Standard Library
  GUI Programming

Python interview questions for 5 years experience

Dictionaries are one of the commonly used data types in Python. You can see the Python Dictionary as an unordered collection of data values with unique keys. It stores values like maps and is mutable in nature.

Implementing Dictionary in Python

// Creating a Dictionary

post = {
	  "user_id": 233,
	  "category_id":2,
	  "title": "Dictionary in Python",  
	  "published_on": "27, Aug, 2019"
	}

Getting an element from Dictionary

x = post["title"]
	print x  // Dictionary in Python

Setting an element in Dictionary

post["tags"]="getting, setting"

A Python Dictionary can hold any data type and are unordered, changeable and indexed.

Dictionaries are one of the commonly used data types in Python. You can see the Python Dictionary as an unordered collection of data values with unique keys. It stores values like maps and is mutable in nature.

Implementing Dictionary in Python

// Creating a Dictionary

post = {
	  "user_id": 233,
	  "category_id":2,
	  "title": "Dictionary in Python",  
	  "published_on": "27, Aug, 2019"
	}

Getting an element from Dictionary

x = post["title"]
	print x  // Dictionary in Python

Setting an element in Dictionary

post["tags"]="getting, setting"

A Python Dictionary can hold any data type and are unordered, changeable and indexed.

Immutable data types or variables are objects that are unchangeable they can't change their state or content. When we try to change the value of Immutable data types after initialization they generate a fatal error.

Examples of Immutable immutable data types in Python are int, float, bool, string, Unicode, tuple.

Example

tupleNumbers = (0, 1, 2, 3)  
tupleNumbers[0] = 5
print(tupleNumbers)

Output: the above line of code generates an error 'tuple' object does not support item assignment because tuple in Python is an Immutable variable and we are trying to change the value after initialization.

One can achieve multithreading in Python language through the import of the threading module. Firstly, you need to install the threadg module on your anaconda environment using the command "conda install –c conda-forge tab".

Monkey Patching in Python is a technique to change/modify the behavior of a class or module dynamically at run-time.

Let understand by an example

# patching.py 
class Base: 
     def func(self): 
          print "func() is being called"

In the below code, we have used patching module and changed the behavior of func() at run-time by assigning a different value.

import patching 
def monkey_func(self): 
     print "monkey_func() is being called"
   
# replacing address of "func" with "monkey_func" 
patching.Base.func = monkey_func 
obj = patching.Base() 
  
# calling function "func" whose address got replaced 
# with function "monkey_func()" 
obj.func() 

Output :monkey_func() is being called

In Python *args and **kwargs are special keyword which allows developers to pass a variable length keyworded or non-keyworded argument to a function. *args is used to pass non-keyworded, variable-length argument list while **kwargs is used keyworded, variable-length argument list.

Example of *args

def sumNumbers(*num):
    sum = 0    
    for n in num:
        sum = sum + n
    print("Sum:",sum)

Example of **kwargs

def concatenateString(**words):
    result = ""
	for arg in words.values():
        result += arg
    return result

print(concatenateString(a="This", b="is", c="an", d="example", e="of",f="**kwargs", g="in", f="Python"))

The difference between range & xrange can be stated as the range() returns a list type object whereas the range() returns a list type object.

Difference between NumPy and SciPy

NumPy SciPy
The full form of NumPy is Numerical Python. SciPy means Scientific Python
NumPy can change the numerical data It is the set of tools for Python language. It supports differentiation, integration and gradient optimization.
NumPy does the basic tasks like indexing and sorting of the data SciPy contains the advanced functions of Algebra
NumPy is faster than SciPy SciPy works at a slow speed

The term Pickling and Unpickling are usually used about serializing and de-serializing the object structure in Python. Pickling means the arrangement of the Python object before writing in the file. You can convert a list into a character stream with the help of Pickling. The character stream has all the essential information to reconstruct the object in the next script. Unpickling in python means extracting the data from the pickle file. It is the process of converting a byte stream into the Python object hierarchy.

Python lambda is an anonymous function that means a function without a name. In Python lambda keyword is used to create an anonymous function in Python. A lambda function has as many arguments but only one expression, which needs to be evaluated and returned.

Example of lambda function in Python

square = lambda x: x*x 
print(square(7)) 

Output:49

The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name.

Examples of mutable data types in Python are list, dictionary, set, and user-defined classes.

Major differences between List and Tuple in Python are

List Tuple

Lists are mutable.

Tuples are immutable.

More efficient as an object can be modified frequently.

Frequent appending to an object is inefficient.

The memory of tuples is inefficient in comparison to Tuples.

The memory of Tuples is found to be more efficient when compared to Lists.

Lists are not easy to debug as they are mutable.

Tuples are easy to debug in comparison to Lists.

Id() function in Python is used to return the identity of an object. This function takes an object as an argument and returns a unique id.

If the value of two objects is the same then id returned by this function is also the same because they are pointing to the same memory address. Example

str1 = "courseya"
print(id(str1)) 
  
str2 = "courseya"
print(id(str2)) 

str3 = "python"
print(id(str1)) 
  
str4 = "id"
print(id(str2)) 

Output:

130252505691449
130252505691449
140252505691870
130252505739928

GIL stands for Global Interpreter Lock. It is a process mutex that allows only a single thread to hold the control of the Python interpreter. The impact of Python Global Interpreter Lock is visible in only the execution of the multi-threaded process, it not visible to developers who are executing single thread process.

Thread in Python means the occurrence of two things at one time. Threads run on different processors but at the same time. Thread safety in Python programming language generally means whether a piece of code is re-entrant or not. Python uses global variables while interpreting user source scripts. This programming language has its threading mechanisms that use thread locking resources for the protection of global variables before changing the values. Locking the mutex to writing new values in the global variables will stop the internal corruption from happening.

Generators in Python language create iterators. In common words, a generator is a type of function in python that returns an object or iterator that we iterate over a value. A generator runs when an iteration uses the "for" statement.

Python decorator is a useful feature that allows developers to alter/change the functionality of an existing behavior of function or class without modifying its structure. You can think Python decorators as a function that can modify the functionality of other functions. Decorators helps us to make our code more clean and shorter. Simple Syntax for defining a Python Decorator

	
@decorator_func
	def say_hello():
		print 'Hello'
Share this post