Top 35 Python Interview Questions for Freshers

Table of Contents:


Prepare for your next Python interview with this comprehensive guide! From foundational knowledge to advanced concepts, this blog covers the most essential Python interview questions that are sure to test your skills. Whether you’re just starting out or looking to level up your expertise, these questions cover topics like Python’s memory management, object-oriented programming, list comprehensions, and much more. By reviewing these questions and answers, you’ll be better equipped to ace your Python interview and demonstrate your proficiency to potential employers.

1. What are the key differences between Python 2 and Python 3?

  • Explanation: This question assesses the candidate’s understanding of Python’s evolution. Key differences include print function syntax, integer division behavior, and Unicode support in Python 3.

2. What are Python decorators, and how do they work?

  • Explanation: This tests knowledge of advanced Python concepts. A decorator is a function that allows modification of another function or method without changing its code.

3. What is the difference between deepcopy and shallow copy in Python?

  • Explanation: This tests knowledge of memory management in Python. A shallow copy copies the reference pointers, while a deep copy creates a full copy of the object and its references.

4. What are the built-in data types in Python?

  • Explanation: Basic understanding of Python’s core data types like lists, tuples, sets, dictionaries, strings, and numbers.

5. How does Python handle memory management?

  • Explanation: This question tests understanding of Python’s garbage collection system, including concepts like reference counting and cyclic garbage collection.

6. What are Python’s list comprehensions?

  • Explanation: A Python feature to create new lists by applying an expression to each item in an iterable. This question checks the candidate’s ability to write concise and efficient code.

7. Explain Python’s Global Interpreter Lock (GIL).

  • Explanation: This is an advanced question that tests understanding of Python’s concurrency model. GIL restricts the execution of multiple threads in CPython, affecting multithreaded programs.

8. What are Lambda functions in Python?

  • Explanation: A lambda function is a small anonymous function defined with the keyword lambda. This tests knowledge of functional programming in Python.

9. Explain the difference between @staticmethod and @classmethod.

  • Explanation: This question tests the candidate’s understanding of object-oriented programming (OOP). A staticmethod does not take any reference to the object, while a classmethod takes a reference to the class.

10. How do you handle exceptions in Python?

  • Explanation: Tests knowledge of error handling using try, except, finally, and else blocks. It also assesses understanding of custom exceptions.

11. What are Python generators, and how do they work?

  • Explanation: A generator is a function that returns an iterator. This question tests knowledge of lazy evaluation and memory-efficient data processing.

12. What is the purpose of the with statement in Python?

  • Explanation: The with statement simplifies exception handling and resource management. It is commonly used for managing files and network connections.

13. What are Python’s built-in functions for handling files?

  • Explanation: Understanding file handling with functions like open(), read(), write(), close(), and context managers.

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

  • Explanation: is checks for object identity (whether two references point to the same object), while == checks for equality (whether the objects have the same value).

15. What are Python’s data structures for working with collections?

  • Explanation: The candidate should discuss lists, tuples, sets, and dictionaries, including their use cases and differences.

16. How does Python support object-oriented programming (OOP)?

  • Explanation: This question assesses knowledge of Python’s OOP features such as classes, inheritance, encapsulation, and polymorphism.

17. What is the self keyword in Python?

  • Explanation: This keyword refers to the instance of the object. It is used in method definitions to access instance variables.

18. What is the purpose of the __init__ method in Python?

  • Explanation: This special method is called when an object is instantiated. It initializes the instance variables.

19. Explain the difference between range and xrange in Python 2.x.

  • Explanation: This question evaluates the candidate’s experience with Python 2.x. xrange returns an iterator, while range returns a list.

20. What are Python’s built-in functions for sorting?

  • Explanation: The candidate should be familiar with sorted() and the sort() method, including their differences and how to sort custom objects.

These questions cover a wide range of Python skills, from basic to advanced topics, and can help assess the candidate’s depth of knowledge and practical experience.

Important Coding Questions

1. Reverse a String Without Using Built-in Functions

Problem: Write a program to reverse a string without using Python’s built-in reverse or slicing methods.

def reverse_string(s):
    # Convert string to list of characters since strings are immutable
    chars = list(s)
    left, right = 0, len(chars) - 1

    # Swap characters from start and end until pointers meet
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1

    # Join characters back into a string
    result = ''
    for char in chars:
        result += char
    return result

# Test the function
print(reverse_string("Hello"))  # Output: "olleH"

2. Check if a Number is Palindrome

Problem: Determine if a number is a palindrome without converting it to a string.

def is_palindrome_number(n):
    # Handle negative numbers (not palindromes)
    if n < 0:
        return False

    # Store original number
    original = n
    reversed_num = 0

    # Reverse the number by extracting digits
    while n > 0:
        digit = n % 10  # Extract last digit
        reversed_num = reversed_num * 10 + digit  # Build reversed number
        n = n // 10  # Remove last digit

    # Compare original with reversed
    return original == reversed_num

# Test the function
print(is_palindrome_number(121))  # Output: True
print(is_palindrome_number(123))  # Output: False

3. Find the Factorial of a Number

Problem: Calculate the factorial of a number using iteration (no recursion or built-ins).

def factorial(n):
    # Handle edge cases
    if n < 0:
        return "Factorial not defined for negative numbers"
    if n == 0 or n == 1:
        return 1

    # Initialize result
    result = 1

    # Multiply numbers from 2 to n
    for i in range(2, n + 1):
        result *= i

    return result

# Test the function
print(factorial(5))  # Output: 120

4. Check if Two Strings are Anagrams

Problem: Check if two strings are anagrams without using sorting or built-ins.

def are_anagrams(str1, str2):
    # Check if lengths are different
    if len(str1) != len(str2):
        return False

    # Create frequency arrays for characters (assuming lowercase a-z)
    freq1 = [0] * 26
    freq2 = [0] * 26

    # Count frequency of characters in str1
    for char in str1:
        freq1[ord(char) - ord('a')] += 1

    # Count frequency of characters in str2
    for char in str2:
        freq2[ord(char) - ord('a')] += 1

    # Compare frequency arrays
    for i in range(26):
        if freq1[i] != freq2[i]:
            return False

    return True

# Test the function
print(are_anagrams("listen", "silent"))  # Output: True
print(are_anagrams("hello", "world"))    # Output: False

5. Find the Largest Element in an Array

Problem: Find the largest element in an array without using max().

def find_largest(arr):
    # Check if array is empty
    if not arr:
        return None

    # Initialize largest as first element
    largest = arr[0]

    # Compare each element with largest
    for i in range(1, len(arr)):
        if arr[i] > largest:
            largest = arr[i]

    return largest

# Test the function
print(find_largest([3, 5, 1, 9, 2]))  # Output: 9

6. Sum of Digits in a Number

Problem: Calculate the sum of digits in a number without converting to string.

def sum_of_digits(n):
    # Handle negative numbers by taking absolute value
    n = abs(n)
    total = 0

    # Extract digits and add them
    while n > 0:
        total += n % 10  # Add last digit
        n //= 10        # Remove last digit

    return total

# Test the function
print(sum_of_digits(123))  # Output: 6

7. Check if a Number is Prime

Problem: Determine if a number is prime without using built-ins.

def is_prime(n):
    # Handle edge cases
    if n <= 1:
        return False
    if n == 2:
        return True

    # Check divisibility up to square root of n
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False

    return True

# Test the function
print(is_prime(17))  # Output: True
print(is_prime(4))   # Output: False

8. Fibonacci Series up to N Terms

Problem: Generate the Fibonacci series up to N terms without recursion.

def fibonacci(n):
    # Handle edge cases
    if n <= 0:
        return []
    if n == 1:
        return [0]

    # Initialize first two terms
    fib = [0, 1]

    # Generate subsequent terms
    for i in range(2, n):
        fib.append(fib[i-1] + fib[i-2])

    return fib

# Test the function
print(fibonacci(6))  # Output: [0, 1, 1, 2, 3, 5]

9. Swap Two Numbers Without a Third Variable

Problem: Swap two numbers without using a temporary variable.

def swap_numbers(a, b):
    # Use arithmetic to swap
    a = a + b  # Add b to a
    b = a - b  # Subtract original b from sum to get original a
    a = a - b  # Subtract new b (original a) from sum to get original b

    return a, b

# Test the function
a, b = 5, 10
a, b = swap_numbers(a, b)
print(a, b)  # Output: 10 5

10. Find GCD of Two Numbers

Problem: Calculate the GCD of two numbers using Euclidean algorithm.

def gcd(a, b):
    # Ensure positive numbers
    a, b = abs(a), abs(b)

    # Keep dividing until remainder is 0
    while b:
        a, b = b, a % b

    return a

# Test the function
print(gcd(48, 18))  # Output: 6

11. Count Vowels in a String

Problem: Count the number of vowels in a string without using built-ins.

def count_vowels(s):
    # Define vowels
    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
    count = 0

    # Iterate through string and count vowels
    for char in s:
        if char in vowels:
            count += 1

    return count

# Test the function
print(count_vowels("Hello"))  # Output: 2

12. Merge Two Sorted Arrays

Problem: Merge two sorted arrays into one sorted array without using sort().

def merge_sorted_arrays(arr1, arr2):
    # Initialize result array and pointers
    merged = []
    i, j = 0, 0

    # Compare elements and merge
    while i < len(arr1) and j < len(arr2):
        if arr1[i] <= arr2[j]:
            merged.append(arr1[i])
            i += 1
        else:
            merged.append(arr2[j])
            j += 1

    # Add remaining elements from arr1
    while i < len(arr1):
        merged.append(arr1[i])
        i += 1

    # Add remaining elements from arr2
    while j < len(arr2):
        merged.append(arr2[j])
        j += 1

    return merged

# Test the function
print(merge_sorted_arrays([1, 3, 5], [2, 4, 6]))  # Output: [1, 2, 3, 4, 5, 6]

13. Find Missing Number in Array

Problem: Find the missing number in an array of 1 to N without using sum().

def find_missing_number(arr, n):
    # XOR of all numbers from 1 to n
    xor_all = 0
    for i in range(1, n + 1):
        xor_all ^= i

    # XOR of all array elements
    xor_arr = 0
    for num in arr:
        xor_arr ^= num

    # Missing number is XOR of xor_all and xor_arr
    return xor_all ^ xor_arr

# Test the function
print(find_missing_number([1, 2, 4, 5], 5))  # Output: 3

14. Remove Duplicates from Array

Problem: Remove duplicates from an unsorted array without using sets.

def remove_duplicates(arr):
    # Initialize result array
    result = []

    # Check each element and add if not already present
    for num in arr:
        found = False
        for res in result:
            if res == num:
                found = True
                break
        if not found:
            result.append(num)

    return result

# Test the function
print(remove_duplicates([1, 3, 5, 3, 1]))  # Output: [1, 3, 5]

15. Check if Array is Sorted

Problem: Check if an array is sorted in ascending order.

def is_sorted(arr):
    # Compare adjacent elements
    for i in range(len(arr) - 1):
        if arr[i] > arr[i + 1]:
            return False

    return True

# Test the function
print(is_sorted([1, 2, 3, 4]))  # Output: True
print(is_sorted([1, 3, 2, 4]))  # Output: False

16. Rotate Array to the Right by K Steps

Problem: Rotate an array to the right by K steps without using extra space.

def rotate_array(arr, k):
    n = len(arr)
    # Handle cases where k > n
    k = k % n

    # Reverse entire array
    reverse(arr, 0, n - 1)
    # Reverse first k elements
    reverse(arr, 0, k - 1)
    # Reverse remaining n-k elements
    reverse(arr, k, n - 1)

    return arr

def reverse(arr, start, end):
    # Swap elements from start to end
    while start < end:
        arr[start], arr[end] = arr[end], arr[start]
        start += 1
        end -= 1

# Test the function
arr = [1, 2, 3, 4, 5]
print(rotate_array(arr, 2))  # Output: [4, 5, 1, 2, 3]

17. Find Second Largest Element in Array

Problem: Find the second largest element in an array.

def second_largest(arr):
    # Check if array has less than 2 elements
    if len(arr) < 2:
        return None

    # Initialize largest and second largest
    largest = arr[0]
    second = None

    # Traverse array
    for i in range(1, len(arr)):
        if arr[i] > largest:
            second = largest
            largest = arr[i]
        elif arr[i] != largest and (second is None or arr[i] > second):
            second = arr[i]

    return second

# Test the function
print(second_largest([5, 2, 9, 1, 7]))  # Output: 7

18. Count Occurrences of a Character in String

Problem: Count occurrences of a specific character in a string.

def count_char(s, char):
    count = 0

    # Iterate through string and count occurrences
    for c in s:
        if c == char:
            count += 1

    return count

# Test the function
print(count_char("hello", "l"))  # Output: 2

19. Find Common Elements in Two Arrays

Problem: Find common elements between two arrays without using sets.

def find_common(arr1, arr2):
    # Initialize result array
    common = []

    # Check each element of arr1 in arr2
    for num1 in arr1:
        for num2 in arr2:
            if num1 == num2:
                # Add to common if not already present
                if num1 not in common:
                    common.append(num1)
                break

    return common

# Test the function
print(find_common([1, 2, 3], [2, 3, 4]))  # Output: [2, 3]

20. Check if String is Balanced (Parentheses)

Problem: Check if a string with parentheses is balanced.

def is_balanced(s):
    # Initialize stack
    stack = []

    # Iterate through string
    for char in s:
        if char == '(':
            stack.append(char)
        elif char == ')':
            if not stack:  # Stack empty, unbalanced
                return False
            stack.pop()  # Remove matching '('

    # Check if stack is empty (fully balanced)
    return len(stack) == 0

# Test the function
print(is_balanced("((()))"))  # Output: True
print(is_balanced("(()"))     # Output: False

21. Find Power of a Number

Problem: Calculate power of a number (a^b) without using ** operator.

def power(a, b):
    # Handle edge cases
    if b < 0:
        return "Negative exponents not supported"
    if b == 0:
        return 1

    # Initialize result
    result = 1

    # Multiply a, b times
    for _ in range(b):
        result *= a

    return result

# Test the function
print(power(2, 3))  # Output: 8

22. Check if Two Strings are Rotations

Problem: Check if one string is a rotation of another.

def are_rotations(str1, str2):
    # Check if lengths are different
    if len(str1) != len(str2):
        return False

    # Double str1 and check if str2 is substring
    temp = str1 + str1
    i, j = 0, 0

    # Manual substring check
    while i < len(temp) and j < len(str2):
        if temp[i] == str2[j]:
            j += 1
        i += 1

    return j == len(str2)

# Test the function
print(are_rotations("abcde", "cdeab"))  # Output: True

23. Find First Non-Repeating Character

Problem: Find the first non-repeating character in a string.

def first_non_repeating(s):
    # Create frequency array
    freq = [0] * 26

    # Count frequency of each character
    for char in s:
        freq[ord(char) - ord('a')] += 1

    # Find first character with frequency 1
    for char in s:
        if freq[ord(char) - ord('a')] == 1:
            return char

    return None

# Test the function
print(first_non_repeating("aabbc"))  # Output: 'c'

24. Multiply Two Numbers Without *

Problem: Multiply two numbers without using the multiplication operator.

def multiply(a, b):
    # Handle negative numbers
    sign = -1 if (a < 0) ^ (b < 0) else 1
    a, b = abs(a), abs(b)
    result = 0

    # Add a to itself b times
    for _ in range(b):
        result += a

    return sign * result

# Test the function
print(multiply(5, 3))  # Output: 15

25. Reverse Words in a Sentence

Problem: Reverse the order of words in a sentence.

def reverse_words(s):
    # Convert string to list for manipulation
    chars = list(s)
    # Reverse entire string
    reverse(chars, 0, len(chars) - 1)

    # Reverse each word
    start = 0
    for i in range(len(chars) + 1):
        if i == len(chars) or chars[i] == ' ':
            reverse(chars, start, i - 1)
            start = i + 1

    # Join back to string
    return ''.join(chars)

def reverse(arr, start, end):
    while start < end:
        arr[start], arr[end] = arr[end], arr[start]
        start += 1
        end -= 1

# Test the function
print(reverse_words("Hello World"))  # Output: "World Hello"

26. Find Pair with Given Sum in Array

Problem: Find a pair in an array with a given sum.

def find_pair(arr, target):
    # Check each pair
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            if arr[i] + arr[j] == target:
                return arr[i], arr[j]

    return None

# Test the function
print(find_pair([2, 4, 3, 5, 7], 9))  # Output: (4, 5)

27. Convert Decimal to Binary

Problem: Convert a decimal number to binary without built-ins.

def decimal_to_binary(n):
    if n == 0:
        return "0"

    binary = ""
    # Extract bits by dividing by 2
    while n > 0:
        binary = str(n % 2) + binary
        n //= 2

    return binary

# Test the function
print(decimal_to_binary(10))  # Output: "1010"

28. Check if Number is Power of 2

Problem: Check if a number is a power of 2.

def is_power_of_two(n):
    # Power of 2 has only one 1-bit in binary
    if n <= 0:
        return False

    # Keep dividing by 2 until odd
    while n > 1:
        if n % 2 != 0:
            return False
        n //= 2

    return True

# Test the function
print(is_power_of_two(8))  # Output: True
print(is_power_of_two(10)) # Output: False

29. Find Middle Element of Linked List

Problem: Find the middle element of a singly linked list (simulated with array).

def find_middle(arr):
    # Use slow and fast pointers
    if not arr:
        return None

    slow = 0
    fast = 0

    # Move fast pointer twice as fast as slow
    while fast < len(arr) and fast + 1 < len(arr):
        slow += 1
        fast += 2

    return arr[slow]

# Test the function
print(find_middle([1, 2, 3, 4, 5]))  # Output: 3

30. Count Set Bits in a Number

Problem: Count the number of 1s in the binary representation of a number.

def count_set_bits(n):
    count = 0

    # Check each bit by right shifting
    while n > 0:
        count += n & 1  # Add 1 if least significant bit is 1
        n >>= 1        # Right shift to check next bit

    return count

# Test the function
print(count_set_bits(13))  # Output: 3 (13 = 1101 in binary)

31. Check if Two Arrays are Equal

Problem: Check if two arrays are equal.

def are_arrays_equal(arr1, arr2):
    # Check lengths first
    if len(arr1) != len(arr2):
        return False

    # Compare each element
    for i in range(len(arr1)):
        if arr1[i] != arr2[i]:
            return False

    return True

# Test the function
print(are_arrays_equal([1, 2, 3], [1, 2, 3]))  # Output: True
print(are_arrays_equal([1, 2], [2, 1]))       # Output: False

32. Find Minimum Distance Between Two Numbers

Problem: Find the minimum distance between two numbers in an array.

def min_distance(arr, x, y):
    min_dist = float('inf')
    prev_index = -1

    # Traverse array and track distance
    for i in range(len(arr)):
        if arr[i] == x or arr[i] == y:
            if prev_index != -1 and arr[prev_index] != arr[i]:
                min_dist = min(min_dist, i - prev_index)
            prev_index = i

    return min_dist if min_dist != float('inf') else -1

# Test the function
print(min_distance([1, 2, 3, 2], 2, 3))  # Output: 1

33. Find Longest Consecutive Sequence

Problem: Find the length of the longest consecutive sequence in an array.

def longest_consecutive(arr):
    if not arr:
        return 0

    # Use a set-like approach with array
    longest = 0
    for num in arr:
        if num - 1 not in arr:  # Start of a sequence
            current = num
            current_streak = 1
            while current + 1 in arr:
                current += 1
                current_streak += 1
            longest = max(longest, current_streak)

    return longest

# Test the function
print(longest_consecutive([1, 9, 3, 10, 4, 20, 2]))  # Output: 4 (1, 2, 3, 4)

34. Check if String Contains Only Digits

Problem: Check if a string contains only digits.

def is_digit_only(s):
    if not s:
        return True

    # Check each character against digit range
    for char in s:
        if ord(char) < ord('0') or ord(char) > ord('9'):
            return False

    return True

# Test the function
print(is_digit_only("123"))  # Output: True
print(is_digit_only("12a3")) # Output: False

35. Find Intersection Point of Two Linked Lists

Problem: Find the intersection point of two linked lists (simulated with arrays).

def find_intersection(arr1, arr2):
    # Get lengths of both arrays
    len1, len2 = len(arr1), len(arr2)

    # Align starting points by skipping extra elements
    diff = abs(len1 - len2)
    i = diff if len1 > len2 else 0
    j = diff if len2 > len1 else 0

    # Traverse both arrays together
    while i < len1 and j < len2:
        if arr1[i] == arr2[j]:
            return arr1[i]
        i += 1
        j += 1

    return None

# Test the function
arr1 = [1, 2, 3, 4, 5]
arr2 = [9, 8, 4, 5]
print(find_intersection(arr1, arr2))  # Output: 4

Conclusion

These 35 Python coding questions cover a wide range of topics—arrays, strings, numbers, and basic data structures—perfect for freshers preparing for interviews. Practice these problems, understand the logic behind each solution, and you’ll be well-equipped to tackle technical interviews. Happy coding!

🔎 Take the Data Science Entrance Test – Boost your career with Cuvette’s placement guarantee! Take the test, and our team will contact you: Start the test now