Here are some hands-on problems to strengthen your understanding of Python Tricks. Try solving them before looking at solutions.
Swap two variables in a single line without using a third variable.
a = 15 b = 25 # Your code here print(a, b) # Expected: 25 15
Generate a list of squares of numbers from 1 to 10 using list comprehension.
# Your code here # Expected: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Create a dictionary with numbers from 1–5 as keys and their cubes as values.
# Your code here # Expected: {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
Combine two lists of names and scores and print them using zip()
.
names = ["Alice", "Bob", "Charlie"] scores = [90, 80, 85] # Your code here # Expected Output: # Alice 90 # Bob 80 # Charlie 85
Use enumerate()
to print items with their positions.
fruits = ["Apple", "Banana", "Cherry"] # Expected Output: # 1 Apple # 2 Banana # 3 Cherry
Reverse the string "interview" using slicing.
# Your code here # Expected: weivretni
Merge two dictionaries into one in a single line.
dict1 = {"x": 1, "y": 2} dict2 = {"z": 3} # Your code here # Expected: {"x": 1, "y": 2, "z": 3}
Given a list of numbers, check if all are even using all()
.
nums = [2, 4, 6, 8] # Your code here # Expected: True
Write a one-line ternary operator to check if a number is even or odd.
num = 11 # Your code here # Expected: "Odd"
Write "Python is powerful" to a file output.txt
using a context manager.
# Your code here
Print: "Alice scored 95 marks" using f-strings.
name = "Alice" score = 95 # Your code here