Here’s an extensive list of 10 Python tips and tricks to help you write cleaner, faster, and more efficient code. Whether you’re a beginner or an experienced developer, these can make a big difference!
Basic Tips and Tricks
- Single-Line If-Else
Quickly assign values based on a condition:
is_raining = True
weather = "Stay indoors" if is_raining else "Go outside"
print(weather) # Output: Stay indoors
- Unpacking Iterables
Assign values to variables from a list or tuple:
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x, y, z) # Output: 10 20 30
- Chained Comparison
Combine multiple comparisons:
num = 15
if 10 < num < 20:
print("Number is between 10 and 20")
- Use
enumerate()for Indexed Loops
Get index and item in a loop:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
# Output: 0 apple, 1 banana, 2 cherry
- Iterating Over Multiple Lists with
zip()
Loop through lists in parallel:
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Output: Alice: 85, Bob: 90, Charlie: 78
- Use
_as a Throwaway Variable
Use _ for values you don’t need:
for _ in range(3):
print("Hello!")
# Output: Hello! (3 times)
elsewithfororwhileLoops
else runs if the loop doesn’t break:
for i in range(5):
if i == 3:
break
else:
print("No break encountered")
# Output: (no output, as break was encountered)
- Sort a List of Dictionaries by a Key
Sort a list based on dictionary keys:
people = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
sorted_people = sorted(people, key=lambda x: x['age'])
print(sorted_people)
# Output: [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}]
- Use
get()to Avoid Key Errors in Dictionaries
get() returns a default value if the key is missing:
person = {"name": "Alice", "age": 30}
city = person.get("city", "Unknown")
print(city) # Output: Unknown
- Reverse a String
Simple way to reverse a string:
text = "Python"
reversed_text = text[::-1]
print(reversed_text) # Output: nohtyP