✅ 10 Python Code Snippets for Interviews & Practice

 

✅ 10 Python Code Snippets for Interviews & Practice 🐍🧠

1. Factorial using recursion

def factorial(n): return 1 if n == 0 else n * factorial(n - 1) print(factorial(5)) # Output: 120

2. Find the second largest number in a list

nums = [10, 20, 30] second_largest = sorted(set(nums))[-2] print(second_largest) # Output: 20

3. Remove punctuation from a string

import string s = "Hello, world!" s_clean = s.translate(str.maketrans('', '', string.punctuation)) print(s_clean) # Output: Hello world

4. Find common elements between two lists

a = [1, 2, 3] b = [2, 3, 4] common = list(set(a) & set(b)) print(common) # Output: [2, 3]

5. Convert a list of words into a string

words = ['Python', 'is', 'fun'] sentence = ' '.join(words) print(sentence) # Output: Python is fun

6. Reverse words in a sentence

s = "Hello World" reversed_s = ' '.join(s.split()[::-1]) print(reversed_s) # Output: World Hello

7. Check if two strings are anagrams

def is_anagram(a, b): return sorted(a) == sorted(b) print(is_anagram("listen", "silent")) # Output: True

8. Get unique values from a list of dictionaries

data = [{'a': 1}, {'a': 2}, {'a': 1}] unique_values = set(d['a'] for d in data) print(unique_values) # Output: {1, 2}

9. Create a dictionary from a range with squares

squares = {x: x**2 for x in range(5)} print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

10. Sort a list of tuples by the second item

pairs = [(1, 3), (2, 1)] sorted_pairs = sorted(pairs, key=lambda x: x[1]) print(sorted_pairs) # Output: [(2, 1), (1, 3)]

💡 Pro Tip:
Practice these snippets for lists, strings, dictionaries, and basic algorithms — they often appear in Python interviews and coding tests.

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