Python Programming for Beginners Part -8

Dr. Virendra Kumar Shrivastava
5 min readSep 15, 2021

Useful Ten One-liners in Python

Sometimes you must be amazed by how effortlessly coding can be done in python. In this post I am going to share some of my beloved one-liners in python programming. You can also access Jupyter notebook to perform tutorial on the same. I am really exited to share with you.

Let’s begin…

Python is one of the most popular programming languages among beginners because it is a beginner’s friendly language. Thanks to Guido van Rossum for making Python syntax supper simple. Python emphasis to follow indentation only. If we talk other programming languages like C, C++, Java etc. they have strict uses of semicolon and curly brackets and so on. It is evident that Python cares for its users and provides one-lines. Although, one-liners are short but powerful as good as tedious codes written in any other programming language or python.

Why should write one-liners?

One-liners empowers programmers to write less codes and achieve more that clearly increases the productivity and save time. The most interesting and exciting part is that writing one-liner codes are fun to read. Use of one-liners codes depict our command in Python languages and showcase your proficiency.

By using Python one-liner, we will be able to code less and achieve more, which directly translates to the increase in productivity.

1. To reverse a list

We can use the reverse method to reverse a list. Most of us are very familiar with the list slicing that is given below:

list1= [10, 20, 30, 40, 50]

list1 = list1[: :-1]

However, list slicing will consume more memory space, so, we recommend using reverse method as given below:

list1.reverse()

2. Swapping the value of two variables

Commonly we use a third variable to perform swap operation. For example,

num1 = 20

num2 =50

temp = num1

num1 = num2

num2 = temp

So, the num1 value is 50 and num2 values is 20 now.

But alternatively, we can try below given one line of code.

num1, num2 = num2, num1

The above one-liner code will produce the same result i.e. the num1 value is 50 and num2 values is 20.

More interestingly, this concept will work with any number of variables. For example

num1 = 10

num2 = 20

num3 = 30

num4 = 40

num5 = 50

num1, num2, nume3, num4, num5 = num5, num4, num3, num2, num1

3. Map method

Python provides the map method that executes a specific function for every element in a list. For example,

list1 = list(map(int, [“10”, “20”, “30”, “40”, “50”]))

print(list1)

Thus, we can typecast the elements in the list into an integer type without iterating through each element by using a loop function that convert element one by one. The map makes it super simple for you.

4. To find common elements in the list

Python provides us a filter method that will find the common element in the two list and removes items that do not match the criteria or not common in both of the lists. For example,

list1 = [10, 20, 30, 40, 50]

list2 = [10, 12, 22, 30, 50]

common_elements = list(filter(lambda item: item in list1, list2))

So, we don’t need to iterate through each element anymore if we use filter method.

5. To find uncommon or not common elements in the list

Python provides us a filter method that will find the uncommon or different element in the two list and removes items are that do not match the criteria or not common in both lists. For example,

list1 = [10, 20, 30, 40, 50]

list2 = [10, 12, 22, 30, 50]

not_common_elements = list(filter(lambda item: item not in list1, list2))

6. List comprehension

Generally, we use for loop to generate a list. For example,

list1 = []

for i in range(10):

list1.append(i)

So, instead of using for a loop to generate a list, we can use list comprehension. For example,

list1 = [i for i in range(10)]

It is also possible to use list comprehension to iterate an existing list that needs to meet the specified criteria by the elements. For example,

list1 = [10, 20, 30, 5, 16, 2, 40, 12, 6,50]

list1 = [i for i in list1 if i > 15]

7. Lambda function / anonymous function

It is one-line anonymous function that is competent to replace a regular function declared with the def keyword. For example

def name(first, middle, last):

return f”{first} {middle} {last}”

myName = name(“Virendra”, “Kumar”,”Shrivastava”)

Alternatively, we can write the above code as given below:

myName = lambda first, middle, last: f”{first} {middlle} {last}”

myName = name(“Virendra”, “Kumar”,”Shrivastava”)

We can use lambda function to generate higher order function. A higher order function may take other function as an argument or may return other function and use of lambda function makes it super simple.

highOrderFunction = lambda n, func: n + func(n)

res1 = highOrderFunction(4, lambda n: n*n)

res2 = highOrderFunction(5, lambda n : n*n*n)

res3 = highOrderFunction(2, lambda n : n*3)

8. To Print the same element multiple times

To print the same element at multiple time, we commonly use iterator for loop. For example

for i in range(10):

print(“Hi”, end = “”)

But we can use one-liner code to do the above task super simply.

print(“Hi”*10)

9. Remove repeated items from a list

To remove repeated numbers from a given list, we can write a one-liner as given below

numbers = [10, 20, 20, 30, 30, 30, 12, 34, 12]

print(list(set(numbers)))

10. Use of Zip function

We can group two inerrable objects in Python with zip() function. The zip() function returns a zip object that maps a similar index of multiple containers ie. Lists, tuple etc. For example

names = list(zip((‘Mrs’, ‘Mr’), [‘Amita’, ‘Jay’]))

Conclusion

In this article, we have presented 10 one-liners that I like most. You can also access Jupyter notebook to perform tutorial on the ten one-lines codes discussed in this article.

On wrapping up notes, feel free to share your comments. Your comments will surely help me to present contents in a better way. See you next week.

--

--

Dr. Virendra Kumar Shrivastava

Professor || Alliance College of Engineering and Design || Alliance University || Writer || Big Data Analytics