Core Python Interview Questions for Freshers

python Interview Questions for Freshers

Python Interview Questions and Answers for Freshers

1. What's the difference between a tuple and a list?

The key difference between tuples and lists is that while tuples are immutable objects, lists are mutable. This means tuples cannot be changed while lists can be modified.

2. What is a dict and what's its most important limitation?

A given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn't make sense to map a particular key more than once.

3. What are the commands that are used to copy an object in Python?

  • copy.copy() function: This makes a copy of the file from source to destination. It returns a shallow copy of the parameter that is passed.
  • copy.deepcopy(): This also creates a copy of the object from source to destination. It returns a deep copy of the parameter that is passed to the function.

4. What is the difference between deep and shallow copy?

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance deep copy is used to store the values that are already copied.

5. How can the ternary operators be used in python?

The ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.

[on_true] if [expression] else [on_false]
x, y = 25, 50
big = x if x < y else y

6. What is the function of negative index?

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

7. Explain delegation in Python?

Delegation is an object oriented technique (also called a design pattern). Let's say you have an object x and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you're interested in changing and delegates all other methods to the corresponding method of x.

8. What is the function of “self”?

“Self” is a variable that represents the instance of the object to itself. Its not an keyword

9. How is “self” explicitly defined in a method?

“Self” is a reference variable and an instance attribute that is used instead of the local variable inside the class.

10. What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code

Python Interview Questions for Freshers

11. What is pass in Python?

The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written.

12. What are modules and packages in Python?

  • Simplicity
  • Maintainability
  • Reusability
  • Scoping

13. What are global, protected and private attributes in Python

  • Global
  • Protected
  • Private

14. What is __init__?

__init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them.

15. What is break, continue and pass in Python?

  • Break - The break statement terminates the loop immediately and the control flows to the statement after the body of the loop.
  • Continue - The continue statement terminates the current iteration of the statement
  • Pass - the pass keyword in Python is generally used to fill up empty blocks

16. What is docstring in Python?

Documentation string or docstring is a multiline string used to document a specific code segment. The docstring should describe what the function or method does.

17. What is slicing in Python?

As the name suggests, ‘slicing’ is taking parts of. Syntax for slicing is [start : stop : step] start is the starting index from where to slice a list or tuple stop is the ending index or where to sop. step is the number of steps to jump. Default value for start is 0, stop is number of items, step is 1. Slicing can be done on strings, arrays, lists, and tuples.

18. What are Python decorators and how would you use them?

In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods without changing their actual code. Decorators allow you to wrap a function with another function, providing a convenient syntax for enhancing or modifying the functionality of the decorated function.

19. How would you setup many projects where each one uses different versions of Python and third party libraries?

Managing multiple projects with different Python versions and dependencies can be done effectively using virtual environments. Virtual environments allow you to create isolated environments for each project, ensuring that they have their own Python interpreter and dependencies.

20. What is PEP8 and do you follow its guidelines when you're coding?

PEP8 is the Python Enhancement Proposal that provides style guide recommendations for Python code. Yes, I follow PEP8 guidelines for consistent and readable code.

21. How are arguments passed – by reference of by value?

In Python, arguments are passed by object reference, meaning the reference to the object is passed, but the value of the reference (not the actual object) is what's copied. This can lead to behavior similar to passing by reference, but immutable objects (e.g., integers, strings) are effectively passed by value.

22. Do you know what list and dict comprehensions are? Can you give an example?

Yes, list and dict comprehensions are concise ways to create lists and dictionaries in Python.

List
squares = [x**2 for x in range(5)]
# Result: [0, 1, 4, 9, 16]
Dict
square_dict = {x: x**2 for x in range(5)}
# Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

23. Show me three different ways of fetching every third item in the list

Using a for loop with a step in range:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = [my_list[i] for i in range(2, len(my_list), 3)]
# Result: [3, 6, 9]

Using list slicing:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = my_list[2::3]
# Result: [3, 6, 9]

Using the filter function with lambda:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] result = list(filter(lambda x: (x + 1) % 3 == 0, my_list)) # Result: [3, 6, 9]

24. Do you know what is the difference between lists and tuples? Can you give me an example for their usage?

Yes, the main difference between lists and tuples in Python is that lists are mutable (can be modified after creation), while tuples are immutable (cannot be modified after creation).

  • my_list = [1, 2, 3, 4, 5]
  • my_list.append(6)
  • # Result: [1, 2, 3, 4, 5, 6]

25. Do you know the difference between range and xrange?

In Python 2, range produces a list, while xrange generates values one at a time using an iterator. In Python 3, range behaves like xrange in Python 2, producing an iterable sequence, and xrange is no longer used.

python Interview Questions

26. How to avoid cyclical imports without having to resort to imports in functions?

Organize code to minimize dependencies, separating concerns into distinct modules, and use techniques like forward declarations or dependency injection to break circular dependencies without relying on function-level imports.

27. what's wrong with import all?

Importing all symbols (from module import *) can lead to namespace pollution, causing potential conflicts and reducing code readability. It's better to use explicit imports for clarity and maintainability.

28. Why is the GIL important?

  • The Global Interpreter Lock (GIL) in CPython (the standard implementation of Python) is important for ensuring thread safety by allowing only one thread to execute Python bytecode at a time
  • While it simplifies memory management, it can limit the parallel execution of threads, impacting performance in CPU-bound and multithreaded scenarios.

29. What are "special" methods (<foo>), how they work, etc

"Special" methods in Python, denoted by double underscores (dunder), such as __foo__, provide a way to customize object behaviors. They are automatically invoked by the interpreter for specific operations like initialization (__init__) or string representation (__str__). By implementing these methods, you can define how instances of your class interact with Python operators and functions.

30. can you manipulate functions as first-class objects?

Yes, in Python, functions are first-class objects, allowing you to assign them to variables, pass them as arguments, return them from other functions, and store them in data structures. This supports a flexible and expressive programming style, including functional programming concepts.

31. What is Python?

Python is a high-level, interpreted programming language known for its readability, versatility, and ease of learning. It supports multiple programming paradigms and has a large standard library, making it widely used for various applications, from web development to data science.

32. What is the lambda function in Python? Why does it exist in Python?

A lambda function in Python is an anonymous, one-line function defined with the lambda keyword. It exists to offer a concise way of creating small, throwaway functions, commonly used in functional programming scenarios where a full function definition is unnecessary or verbose.

33. What is pass in Python?

In Python, pass is a null statement that serves as a no-operation placeholder. It is used when syntactically some code is required but no action is desired or necessary. pass essentially does nothing and is often used as a temporary placeholder during development or in situations where the code structure requires a statement but no specific action.

34. What is *args, **kwargs in function definition?

In Python, *args allows a function to accept a variable number of positional arguments as a tuple, while **kwargs allows the acceptance of a variable number of keyword arguments as a dictionary. This flexibility enables functions to handle diverse inputs without explicitly specifying all parameters.

35. What is docstring in Python? How to write them? Are they required?

a docstring is a string literal used to document modules, classes, functions, or methods. They are written using triple-quotes and, while not mandatory, are recommended for enhancing code readability and generating documentation.

36. What are the built-in data types that Python provides? Which of them are mutable, which are immutable?

Immutable Data Types:

  • int: Integer type (immutable).
  • float: Floating-point type (immutable).
  • complex: Complex number type (immutable).
  • str: String type (immutable).
  • tuple: Tuple type (immutable).

Mutable Data Types:

  • list: List type (mutable).
  • dict: Dictionary type (mutable).
  • set: Set type (mutable).

37. What is the difference between list and tuple types in Python?

Lists in Python are mutable (modifiable), defined with square brackets, and suitable for situations where elements may need to be added, removed, or modified. Tuples are immutable (unchangeable), defined with parentheses, and preferred for situations where data should remain constant, offering better performance for iteration and indexing.

38. What keywords can be used in conjunction with the for keyword?

Keywords that can be used in conjunction with the for keyword in Python include:

in : Used to iterate over elements in a sequence or iterable.
Example:
for item in iterable:
# Code block
range : Generates a sequence of numbers to iterate over.
for i in range(5):
# Code block
These keywords enhance the functionality of the for loop for various iteration scenarios.

39. What could be the key in dict?

In a Python dictionary, keys can be of almost any immutable data type. Common examples include:

  • integers
  • floats
  • strings
  • tuples

40. What's the difference between globals(), locals(), and vars()?

In Python, globals() returns the global symbol table, locals() returns the local symbol table, and vars() is equivalent to locals() without arguments. Modifications to globals() affect global variables, while changes to locals() do not impact variables in the global scope.

Full Stack Interview Questions

41. What is PEP8?

PEP8 is the Python Enhancement Proposal that provides style guide recommendations for writing clean, readable code in Python. It covers conventions for formatting, naming, and structure to promote code consistency.

42. What is slicing in Python?

Slicing in Python refers to the technique of extracting a portion (a subsequence) of a sequence object, such as a list, string, or tuple, using a specified start, stop, and step. The syntax is sequence[start:stop:step].

43. Is it possible to have a negative index in iterative types in Python?

Yes, negative indexing is possible in Python for iterable types like lists, strings, and tuples. Negative indices count from the end of the sequence, making it convenient to access elements from the reverse.

44. What is the __init__.py module? What it's for?

The __init__.py module in Python signifies that a directory should be treated as a package. It can be empty or contain package-level initialization code, and its presence is essential for recognizing the directory as part of a package.

45. How can I swap values of variables in Python?

  • You can swap values of variables in Python using tuple unpacking:
  • a, b = b, a

46. How do I view object methods?

To view object methods in Python, use dir(object) to list all attributes and methods. Detailed documentation for methods can be accessed with help(object.method).

  • object_methods = dir(object)
  • print(object_methods)

47. How do you get documentation on objects' methods in Python?

In Python, obtain documentation for an object's methods using help(object.method). This provides detailed information about the method and its usage.

48. What is a module in python? What is a package? What is the difference between packages and modules in Python?

In Python, a module is a single file containing Python code, while a package is a directory containing multiple modules along with a special __init__.py file. Modules offer a way to organize code, and packages provide a hierarchical structure for better organization and reusability.

49. Can you write multithreading applications in Python? What is the difference between multithreading and multiprocessing?

Yes, Python supports multithreading. The key difference between multithreading and multiprocessing is that multithreading shares the same memory space, while multiprocessing uses separate processes with independent memory, making it more suitable for CPU-bound tasks.

50. What is a decorator? How to create a custom decorator?

In Python, a decorator is a design pattern allowing the modification or enhancement of functions/methods. To create a custom decorator, define a function that takes another function as an argument, adds desired functionality, and returns the modified function

def my_decorator(func):

  • def wrapper(*args, **kwargs):
    • print("Before function execution")
    • result = func(*args, **kwargs)
    • print("After function execution")
    • return result
  • return wrapper
  • @my_decorator
  • def my_function():
    • print("Inside the function")
  • my_function()

51. What is @classmethod, @staticmethod, @property?

In Python, @classmethod is a decorator for defining class methods, @staticmethod is for static methods, and @property is used to create read-only properties in classes. They provide different ways to define and use methods within classes.

52. Does Python fully support OOP?

Yes, Python fully supports Object-Oriented Programming (OOP) with features like classes, inheritance, encapsulation, and polymorphism. It allows developers to implement OOP principles to create modular and reusable code.

53. What is the __dict__ attribute of an object in Python?

In Python, the __dict__ attribute of an object is a dictionary containing its attributes and their values. It provides a dynamic view of the object's state, allowing inspection and modification of attributes at runtime.

54. What the self is used for in Python?

In Python, self is a convention used as the first parameter in instance methods, representing the instance calling the method. It allows access to instance variables and ensures proper binding of the method to the instance.

55. What is the __init__ method used for?

The __init__ method in Python is a special method used for initializing object attributes when an instance is created. It is automatically called when a new object is instantiated from a class, allowing the setting of initial values and performing setup tasks.

56. Explain how to make a Python script executable on Unix?

To make a Python script executable on Unix, add a shebang line at the script's beginning, such as #!/usr/bin/env python3. Then, make the script executable using the chmod +x script.py command, allowing it to be run as ./script.py.

57. What is pickling and unpickling(marshaling and unmarshaling)?

Pickling in Python refers to the process of serializing objects into a byte stream, while unpickling involves deserializing the byte stream back into objects. It is used for data persistence and transmission, akin to marshaling and unmarshaling in other programming languages.