Day 22: Python Shortcuts to write Cleaner and more Efficient Code
1. List Comprehensions
# Instead of
squares = [ ]
for i in range(10):
squares.append(i**2)
#Use
squares = [ i**2 for i in range(10)]
2. Dictionary Comprehensions
# Instead of
squares_dict = {}
for i in range(10):
squares_dict[i] = i**2
# Use
squares_dict = { i : i**2 for i in range(10)}
3. Multiple Assignments
# Instead of
a=1
b=2
c=3
#Use
a, b, c = 1, 2, 3
4. String Join
# Instead of:
words = ['Python', 'is', 'awesome']
sentence = ''
for word in words:
sentence += word+' '
#Use
sentence = ' '.join(words)
5. Conditional Expressions (Ternary Operator)
# Instead of
if condition:
x = a
else:
x = b
#Use
x = a if condition else b
6. Use of enumerate for Index
# Instead of
index = 0
for item in items:
print(index, item)
index +=1
# Use
for index, item in enumerate(items):
print(index, item)
7. Zip for Parallel Iteration
# Instead of:
for i in range(len(list1)):
print(list1[i], list2[i])
#Use
for item1, item2 in zip(list1,list2):
print(item1, item2)
8. all and any
# Instead of
for item in items:
if not condition(item):
check = False
break
# Use
check = all(condition(item) for item in items)
9. Context Managers (with statement)
# Instead of
file = open('file.txt','r')
try:
content = file.read()
finally:
file.close()
#Use
with open('file.txt','r') as file:
content = file.read()
10. get Method for Dictionaries
#Instead of
if key in dict:
value = dict[key]
else:
value = default
# Use
value = dict.get(key, default)
#Python #100DaysOfCode #Shortcuts