Python one-liner superb tricks

Akshay Jain
4 min readApr 16, 2022

--

Photo by Jess Bailey on Unsplash

Still many developer are their who just write code, to just complete the assigned task and follows some old pattern or tactics to write the code. But one thing I want to add here, just don’t forget that you are writing code in Python Language… You have super saiyan power to write code in very easy, efficient and faster way.

1. List Comprehension

Lets first see why we want to use list comprehension.

even_numbers = []
for i in range(1, 10):
if i %2 == 0:
even_numbers.append(i)
print(even_numbers) # [2,4,6,8]

The above code is to get the even number between the range of 1-10 . So for that first we have declared the empty list even_numbers … further we loop through the number between 1-10 and check for the even number and if the number is even then we append the value in then list even_numbers . So to do this we have to write 4 line of code. What if I say Python provides elegant approach to create list in just single line…

even_numbers = [i for i in range(1, 10) if i % 2 == 0]
print(even_numbers) #[2,4,6,8]

By looking above code you can know that how the super trick python provides and even it looks pretty simple.

This is just the example of use of list comprehension, but python also support comprehension for dict , set and generator .

# dict comprehensionprepare_dict = {i:i ** 2 for i in range(1, 10) if i % 2 == 0}
Output: {2: 4, 4: 16, 6: 36, 8: 64}
--- ---# set comprehensionsample_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
prepare_set = {i for i in sample_list if i % 2 == 0}
Output: {2, 4, 6}

2. map function

In the above point we have seen the use of List comprehension to prepare the list. Let say if we want to perform some operation for each item in list, then we can easily make use of map method in python. Let’s see example to use map .

def my_fun(item):
# can be multiple line of code
return item ** 2
prepare_list = list(map(my_fun, range(1, 5)))
print(prepare_list)

In above code, we used the map method. 1st parameter is my_fun method which is used to perform some operation for each of the item in the list and at last it return the item and like this it iterates through all items given in the 2nd parameter.

3. filter function

Filter is use to match the value with specific condition and if the condition is true then only the item will return, otherwise it will not return any other value not even the null value.

def my_fun(item):
# can be multiple line of code
return (item) % 2 == 0
prepare_list = list(filter(my_fun, range(1, 5)))
print(prepare_list) # [2, 4]

If you think, it looks same as map then let me tell you, it is not same. If you use map instead of filter then your output will be in Boolean , but filter return the actual item, if condition is true .

4. reduce function

reduce function is use to iterate and calculate the single cumulative value like find max value, sum of numbers etc.

# code to find max number from listnumbers = [3, 5, 20, 14, 77, 2]
max_num, *numbers = numbers
for num in numbers:
if num > max_num:
max_num = num

print(max_num) # 77

We sometime in very hurry to write code, and we don’t think about the code and even the complexity of code. So let me know you the best way to make write the code in the alternate way.

from functools import reducenumbers = [3, 5, 20, 14, 77, 2]
max_num = reduce(lambda prev, next: prev if prev > next else next, numbers)

print(max_num) # 77

Like this you can use reduce for reduction.

5. lambda function

lambda function is anonymous function, which accepts any number of arguments , but it only have single statement.

# code to remove extra space from given stringimport re
my_val = ' a b cdef '
remove_extra_space = lambda val: re.sub('\s+', ' ', val)
print(remove_extra_space(my_val))
output: a b cdef

Bonus tip:

Typecast whole list item

z = ['1', '2', '3', '4', '5']
z = list(map(int, z))
print(z)
output: [1, 2, 3, 4, 5]

Above code is the example to convert all the item present in string to int type. This is the simple one-liner code to do this type casting in whole list.

Thanks a bunch for giving you precious time to read the article. I hope it is helpful to you. If you have some more tactics then you can share in the comment section.

--

--

Akshay Jain
Akshay Jain

Written by Akshay Jain

Full-Stack Developer | Python | React JS | PostgreSQL

Responses (4)