Some Helpful Tricks
In this lesson, we'll see some useful Pythonic tricks.
List Comprehension
The list comprehension is a well-known python construct. Here are some tricks with a list in Python:
List Initialization of Size N
Here is to initialize a list of size ‘N’ in Pythonic way:
lst = [0] * 5 # A list of size 5 initialized with zeros.print(lst)
filter
Function
If the problem is similar to find positive integers then instead of writing:
for x in lst:
if x % 2 is 0:
print(x)
We can use filter and lambda functions as follows:
# A list contains both even and odd numbers.seq = [0, 1, 2, 3, 5, 8, 13]# result contains odd numbers of the listresult = filter(lambda x: x % 2, seq)print(list(result))
map
function
If the problem is similar to double all integers in a list then instead of writing:
for x in range(len(lst)):
lst[i] = lst[i] + lst[i]
We can use map and lambda functions as follows:
# Double all numbers using map and lambdanumbers = (1, 2, 3, 4)result = map(lambda x: x + x, numbers)print(list(result))
in
Operator
If the problem is similar to find something in a list then instead of writing:
for i in range(len(lst)):
if lst[i] == number:
print("True")
We can use in
operator as follows:
number = 3found = number in [1, 2, 3, 4, 5]print(found)
enumerate
Function
In scenarios where you may want to access the index of each element in a list, it’s better you employ the enumerate
function instead of:
lst = list(range(10))
index = 0
while index < len(lst):
print(lst[index], index)
index += 1
lst = list(range(5))for index, value in enumerate(lst):print(value, index)
Dictionary Comprehension
Dict Comprehension’s purpose is similar to construct a dictionary using a well-understood comprehension syntax.
Bad:
emails = {}
for user in users:
if user.email:
emails[user.name] = user.email
We can replace the above code with this neat code:
emails = {user.name: user.email for user in users if user.email}
Set Comprehension
The set comprehension syntax is relatively new and often overlooked. Just as lists, sets can also be generated using a comprehension syntax.
Bad:
elements = [1, 3, 5, 2, 3, 7, 9, 2, 7]
unique_elements = set()
for element in elements:
unique_elements.add(element)
print(unique_elements)
We can replace the above code with this neat code:
elements = [1, 3, 5, 2, 3, 7, 9, 2, 7]unique_elements = {element for element in elements}print(unique_elements)
Unnecessary Repetition
We can avoid unnecessary repeated lines in Python. Suppose if we want to print:
print('------------------------------')
print("Educative")
print('------------------------------')
The above code can be replaced with:
print('{0}\n{1}\n{0}'.format('-'*30, "Educative"))