🐍 Top Python Interview Questions (With Code Examples)

Posted by

Python interview questions code exampleIntroduction

Python is one of the most popular languages for technical interviews, especially in SRE, Platform Engineering, and DevOps roles. In this post, I’ll share commonly asked Python interview questions, along with short explanations.

Strings

  • Reverse a string
  • Palindrome check
  • Anagram check
  • 💡 Interview Tip: Be ready to explain time complexity (O(n)) when asked about string problems.
  • “For more details, see the Python official string documentation.”

Lists

  • Find duplicates in a list
  • Flatten nested list
  • 💡 SRE Insight: Flattening lists is useful when parsing JSON logs or API responses.
  • “You can explore more list operations in the Python docs on lists (docs.python.org in Bing).”

Numbers

  • Prime number check
  • Factorial (recursive)
  • Swap without third variable
  • 💡 Interview Tip: Compare recursion vs iteration for factorial — mention stack depth and efficiency.

Algorithms

  • Binary search
  • Bubble sort
  • 💡 SRE Insight: Sorting algorithms are rarely hand‑coded in production, but knowing them shows you understand fundamentals.
  • “If you want to practice these problems, check out LeetCode’s Python problem set (leetcode.com in Bing).”

 Dicts & Collections

  • Sort dictionary by value
  • Word frequency counter

 File Handling

  • Count lines in file
  • Parse CSV file
  • “The Real Python tutorial on file handling (realpython.com in Bing) is a great resource for deeper learning.”

 OOP & Error Handling

  • Class with inheritance
  • Try/except block
  • 💡 Interview Tip: Be prepared to explain encapsulation and polymorphism with simple class examples.

👉 Note: All code snippets are grouped in one section below so you can easily copy them and test on your machine without scrolling back and forth.

# Reverse a string
s = "Python"
print(s[::-1])

# Palindrome check
s = "madam"
print(s == s[::-1])

# Anagram check
from collections import Counter
print(Counter("listen") == Counter("silent"))

# Find duplicates in a list
nums = [1,2,3,2,4,1]
dupes = [x for x in set(nums) if nums.count(x) > 1]

# Flatten nested list
nested = [[1,2],[3,4],[5]]
flat = [x for sub in nested for x in sub]

# Prime number check
def is_prime(n):
return all(n % i for i in range(2,int(n**0.5)+1)) and n>1

# Factorial (recursive)
def fact(n): return 1 if n==0 else n*fact(n-1)

# Swap without third variable
a,b=5,10
a,b=b,a

# Binary search
def bsearch(arr,x):
l,r=0,len(arr)-1
while l<=r:
m=(l+r)//2
if arr[m]==x: return m
elif arr[m]<x: l=m+1
else: r=m-1

# Bubble sort
arr=[5,3,1,4]
for i in range(len(arr)):
for j in range(len(arr)-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]

# Sort dictionary by value
data={"a":3,"b":1,"c":2}
print(sorted(data.items(), key=lambda x:x[1]))

# Word frequency counter
from collections import Counter
text="this is a test this"
print(Counter(text.split()))

# Count lines in file
with open("file.txt") as f:
print(sum(1 for _ in f))

# Parse CSV file
import csv
with open("data.csv") as f:
for row in csv.reader(f):
print(row)

# Class with inheritance
class Animal: 
def speak(self): print("sound")
class Dog(Animal): 
def speak(self): print("bark")

# Try/except block
try:
x=int("abc")
except ValueError:
print("Invalid number")

Conclusion

These Python interview questions cover most of what you’ll face in coding rounds for Python developer, SRE, Platform Engineer, and DevOps roles. Practice writing the code, then explain the logic in one line — that’s what impresses interviewers.

👉 Next in this series: Advanced Python Interview Questions (decorators, generators, context managers).

Leave a Reply

Your email address will not be published. Required fields are marked *