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:
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:
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:
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:
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
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:
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:
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: