✅ 10 Essential Python Interview Code Snippets

 

✅ 10 Essential Python Interview Code Snippets 🐍💼

1. Reverse a string

s = "hello" print(s[::-1]) # Output: 'olleh'

2. Check if a string is a palindrome

def is_palindrome(s): return s == s[::-1] print(is_palindrome("level")) # Output: True

3. Count word frequency in a list

from collections import Counter words = ['apple', 'banana', 'apple'] freq = Counter(words) print(freq) # Output: Counter({'apple': 2, 'banana': 1})

4. Swap two variables

a, b = 5, 10 a, b = b, a print(a, b) # Output: 10 5

5. Fibonacci sequence using recursion

def fib(n): return n if n <= 1 else fib(n-1) + fib(n-2) print(fib(6)) # Output: 8

6. Find duplicate elements in a list

lst = [1, 2, 3, 2, 4] duplicates = set(x for x in lst if lst.count(x) > 1) print(duplicates) # Output: {2}

7. Check if a list is sorted

def is_sorted(lst): return lst == sorted(lst) print(is_sorted([1, 2, 3])) # Output: True print(is_sorted([3, 2, 1])) # Output: False

8. Flatten a 2D list

matrix = [[1, 2], [3, 4]] flat = [num for row in matrix for num in row] print(flat) # Output: [1, 2, 3, 4]

9. Read a file line by line

with open('file.txt') as f: for line in f: print(line.strip())

10. Using lambda and map

nums = [1, 2, 3] squares = list(map(lambda x: x**2, nums)) print(squares) # Output: [1, 4, 9]

💡 Pro Tip:
Practice variations of these snippets with lists, strings, dictionaries, and file handling. These are common patterns in Python interviews.

Comments

Popular posts from this blog

🔁 Top 30 Python List Methods You Should Know

Python Project 7: Read & Write JSON Files

✅ Python – Quick Start Guide for Beginners