Python Interview Questions

Ace Your Interview: Top 50 Python Interview Questions

Basic Python Concepts

1. What is Python?

Python is a high-level, interpreted, general-purpose programming language. It emphasizes code readability with its notable use of significant indentation.

2. What are the key features of Python?

Easy to learn and read, interpreted language, large standard library, cross-platform compatibility, open-source, object-oriented, dynamic typing.

3. What is the difference between lists and tuples in Python?

Lists are mutable (changeable), while tuples are immutable (unchangeable). Lists use square brackets [], and tuples use parentheses ().

4. What is a dictionary in Python?

A dictionary is an unordered collection of key-value pairs. It’s mutable and uses curly braces {}.

5. What is PEP 8?

PEP 8 is a style guide for Python code, recommending coding conventions for readability.

6. What is the difference between == and is in Python?

== checks for equality of value, while is checks if two variables refer to the same object in memory.

7. What are Python decorators?

Decorators modify the functionality of a function without changing its code. They are denoted by the @ symbol.

8. What are lambda functions in Python?

Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression.

range() returns a list, while xrange() returns a generator object (more memory-efficient). In Python 3, range() behaves like xrange().

10. What is the __init__ method in Python?

The __init__ method is a constructor that’s called when an object is created from a class. It initializes the object’s attributes.

Intermediate Python Concepts

11. What is a generator in Python?

A generator is a function that returns an iterator. It yields values one at a time, saving memory.

12. What is a Python iterator?

An iterator is an object that allows you to traverse through a collection of data. It implements the __iter__ and __next__ methods.

13. What is the Global Interpreter Lock (GIL)?

The GIL is a mutex that allows only one thread to execute Python bytecode at a time. This simplifies memory management but limits parallelism in multi-threaded programs.

14. What is exception handling in Python?

Exception handling is a mechanism to handle runtime errors. It uses try, except, finally, and raise blocks.

15. What is a module in Python?

A module is a file containing Python definitions and statements. It allows you to organize code into reusable components.

16. What is a package in Python?

A package is a collection of modules (a directory with an __init__.py file). It allows you to organize modules into a hierarchical namespace.

17. What is the with statement in Python?

The with statement is used for resource management, ensuring that resources like files are properly closed.

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

A shallow copy creates a new object but references the original elements. A deep copy creates a new object and copies all elements recursively.

19. How do you handle memory management in Python?

Python uses automatic memory management (garbage collection). Reference counting and a cyclic garbage collector are used.

20. Explain Python’s *args and **kwargs syntax.

*args allows a function to accept a variable number of positional arguments. **kwargs allows a function to accept a variable number of keyword arguments.

Advanced Python Concepts

21. What are metaclasses in Python?

Metaclasses are classes that create classes. They define how a class behaves.

22. What is the purpose of the __name__ == "__main__" condition?

It checks if the script is being run directly or imported as a module.

23. Explain Python’s asynchronous programming (async/await).

async/await allows you to write concurrent code using coroutines, enabling non-blocking I/O operations.

24. What is a virtual environment in Python?

A virtual environment is an isolated Python environment that allows you to install packages without affecting the system-wide Python installation.  

25. What are Python’s built-in data types?

Numbers (integers, floats, complex), strings, lists, tuples, dictionaries, sets, and booleans.

26. What is pickling and unpickling in Python?

Pickling is the process of serializing (converting) a Python object into a byte stream. Unpickling is the reverse process.

27. What are context managers in Python?

Context managers define a runtime context that is executed with the with statement.

28. Explain the purpose of __slots__ in Python classes.

__slots__ limits the attributes that an object can have, saving memory and improving performance.

29. What are descriptors in Python?

Descriptors are objects that implement the descriptor protocol (__get__, __set__, __delete__). They can control attribute access.

30. What is the difference between static methods and class methods?

Static methods don’t have access to the instance or class. Class methods have access to the class itself.

Python Libraries and Frameworks

31. What is NumPy, and what are its uses?

NumPy is a library for numerical computing. It provides support for arrays and matrices.

32. What is Pandas, and what are its uses?

Pandas is a library for data manipulation and analysis. It provides DataFrames and Series.

33. What is Flask or Django, and what are their uses?

Flask and Django are web frameworks. Flask is a microframework, and Django is a full-stack framework.

34. What is Matplotlib, and what are its uses?

Matplotlib is a library for data visualization.

35. What is Scikit-learn, and what are its uses?

Scikit-learn is a library for machine learning.

36. What is requests library used for?

The requests library is used for making HTTP requests.

37. What is the use of the unittest module?

The unittest module is used for writing and running unit tests.

38. What is the purpose of the OS module?

The OS module provides functions for interacting with the operating system.

39. What is the purpose of the sys module?

The sys module provides access to system-specific parameters and functions.

40. What is the purpose of the datetime module?

The datetime module provides classes for working with dates and times.

41. Write a Python program to reverse a string.

Python
 
def reverse_string(s):
  """Reverses a given string."""
  return s[::-1]

# Example usage
string = "hello"
reversed_string = reverse_string(string)
print(reversed_string)  # Output: olleh

42. Write a Python program to check if a number is prime.

Python
 
def is_prime(n):
  """Checks if a number is prime."""
  if n <= 1:
    return False
  for i in range(2, int(n**0.5) + 1):
    if n % i == 0:
      return False
  return True

# Example usage
number = 17
if is_prime(number):
  print(f"{number} is a prime number.")
else:
  print(f"{number} is not a prime number.")

43. Write a Python program to find the factorial of a number.

Python
 
def factorial(n):
  """Calculates the factorial of a number."""
  if n == 0:
    return 1
  else:
    return n * factorial(n - 1)

# Example usage
number = 5
result = factorial(number)
print(f"The factorial of {number} is {result}.") #Output: The factorial of 5 is 120.

44. Write a Python program to implement the Fibonacci sequence.

Python
 
def fibonacci(n):
  """Generates the Fibonacci sequence up to n terms."""
  fib_list = []
  a, b = 0, 1
  for _ in range(n):
    fib_list.append(a)
    a, b = b, a + b
  return fib_list

# Example usage
terms = 10
fib_sequence = fibonacci(terms)
print(fib_sequence) #Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

45. Write a Python program to sort a list.

Python
 
def sort_list(lst):
  """Sorts a list in ascending order."""
  return sorted(lst)

# Example usage
my_list = [5, 2, 8, 1, 9]
sorted_list = sort_list(my_list)
print(sorted_list) #Output: [1, 2, 5, 8, 9]

46. Write a Python program to remove duplicates from a list.

Python
 
def remove_duplicates(lst):
  """Removes duplicates from a list."""
  return list(set(lst))

# Example usage
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = remove_duplicates(my_list)
print(unique_list) #Output: [1, 2, 3, 4, 5]

47. Write a Python program to find the most frequent element in a list.

Python
 
def most_frequent(lst):
  """Finds the most frequent element in a list."""
  counts = {}
  for item in lst:
    counts[item] = counts.get(item, 0) + 1
  max_count = 0
  most_common = None
  for item, count in counts.items():
    if count > max_count:
      max_count = count
      most_common = item
  return most_common

# Example usage
my_list = [1, 2, 2, 3, 3, 3, 4]
frequent_element = most_frequent(my_list)
print(f"The most frequent element is: {frequent_element}") #Output: The most frequent element is: 3

48. Write a Python program to check if a string is a palindrome.

Python
 
def is_palindrome(s):
  """Checks if a string is a palindrome."""
  s = s.lower().replace(" ", "") #remove spaces and set to lowercase.
  return s == s[::-1]

# Example usage
string1 = "madam"
string2 = "hello"
print(f"'{string1}' is a palindrome: {is_palindrome(string1)}") #Output: 'madam' is a palindrome: True
print(f"'{string2}' is a palindrome: {is_palindrome(string2)}") #Output: 'hello' is a palindrome: False

49. Write a Python program to read a file and count the number of words.

Python
 
def count_words(filename):
  """Reads a file and counts the number of words."""
  try:
    with open(filename, 'r') as file:
      text = file.read()
      words = text.split()
      return len(words)
  except FileNotFoundError:
    return "File not found."

# Example usage (assuming a file named "text.txt" exists)
word_count = count_words("text.txt")
print(f"Word count: {word_count}")

50. Write a python program that uses list comprehension to generate a list of the squares of the numbers 1 through 10.

Python
 
squares = [x**2 for x in range(1, 11)]
print(squares) #Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Popular Courses

Leave a Comment