What will we cover?
In this tutorial you will learn why One Liners is something beginners focus on and senior developers don’t waste their time on. But You will learn some useful things you can do in one line of Python code.
Why are One-Liners not (always) good?
Why are one-liners are bad?
If I could say it one word: Readability.
Most beginners, I was the same, are focus on solving the problem, and later, often solving it in some impressive way.
Why do senior developers not do that? Well, they spend hours debugging code – code should be easy to understand and maintain.
Yes, senior developers know that code that can written in one line, is often difficult to get useful stack traces from, when they fail. They know it is better to focus on breaking the code up in multiple lines. This makes the stack trace easier to get the error. Also, it enhances the readability of the code. Which makes it easier to understand and therefore to maintain.
Now let’s dive into 15 useful things you still can do in one line of Python code without compromising readability.
#1 Swap Two Variables
This one might not be fully appreciated if you have not been coding in another language.
Take a moment and think about the following problem.
You have two drinks.

Your job is to switch the content of the glass. That is, the blue drink should be in the glass of the red drink, and vice verse.
Obviously, to do this, you need a third glass or something similar.
This is the same problem when you need to swap (switch) the the “content” of two variables.
As you need to do this often as a programmer, Python has made this easy for you.
a = 10
b = 20
print(a, b)
# Swap the two variables
a, b = b, a
print(a, b)
This will swap the content. First print will output 10 20 and second 20 10.
#2 Reverse a List
First of all, Python lists are amazing. Again, if you worked with other programming languages, you will fall in love with how easy it is to work with Python lists.
Anyhow, sometimes you need to get the content from a list in reversed order.
This can be done easily as follows.
l = [1, 2, 3, 4, 5]
print(l[::-1])
This will output 5, 4, 3, 2, 1.
Check out the last bonus trick how this can be useful to know for a job interview.
#3 Calculate the mode of a list
First of all, what is the mode of a list?
Good question my friend. It is the most common element in a list. This is often useful to know.
Let’s see how this can be done.
l = [1,3,2,5,2,2,5,4]
mode = max(set(l), key=l.count)
print(mode)
This will output 2, as it is the most common element.
How to understand the code?
I am happy you asked.
The set(l) gives a set of the list, which is all the unique element in the list. Here it give {1, 3, 2, 5, 4}.
Then max(set(l), key=l.count) gives the maximum value of each value in set with the count of it. Hence, you get the value with the highest count.
#4 Strip lines for start and end spaces and remove new lines
When you read lines from a text file, it can have leading and ending spaces, as well as lines with no content.
This is an example of lines read from a text file.
lines = [' THE ADVENTURE OF THE NOBLE BACHELOR\n',
'\n',
' The Lord St. Simon marriage, and its curious termination, have long\n']
To remove (or strip) for leading and ending spaces, you can do the following.
lines = [line.strip() for line in lines]
print(lines)
Which will result in.
['THE ADVENTURE OF THE NOBLE BACHELOR',
'',
'The Lord St. Simon marriage, and its curious termination, have long']
Notice it also remove new lines.
If you want to remove empty lines. This can be done as follows.
lines = [line for line in lines if len(line) > 0]
print(lines)
This will result in.
['THE ADVENTURE OF THE NOBLE BACHELOR',
'The Lord St. Simon marriage, and its curious termination, have long']
#5 Multiple variable assignment
Sometimes code can become really long, if you have a lot of variable you need to assign to specific values.
This can be done in one line.
a, b, c = 4.4, 'Awesome', 7
print(a)
print(b)
print(c)
This will output.
4.4
Awesome
7
Notice the different types of the variables.
#6 Convert a string into a number
I actually love this one. Why? Because in Python it just a built-in function to convert a string to number.
my_str = '27'
my_int = int(my_str)
print(my_int, type(my_int))
my_str = '3.14'
my_float = float(my_str)
print(my_float, type(my_float))
It will print the values and the type of the variables, int and float, respectively.
#7 Type casting a list of items
This is a great use of List Comprehension.
Say, you have a list of strings with integers. It can happen you read a text file, and each line has integers. Then you need to convert them to integers to use the values.
This can be done as follows.
l = ['12', '23', '34']
items = [int(i) for i in l]
Wow. Did you see that? We just used what we learned in last step and combine it with List Comprehensions.
#8 Find the square root of a number
This is quite handy to know how to take the square root of a number without using math libraries.
print(16**.5)
Well, the 16**.5 syntax (the double **) puts the value (here 16) to the power of the exponent (here .5). This lifts 16 to the power of a half (.5). This is the same as taking the square root.
Hence, it will print 4.
#9 How to get the cube root of a number
This one is almost the same. But remember, you get a bonus one in the end, so you will get 15 one-liners that useful, if you feel cheated by this one.
The cube root means, given a number x, find a number y such that y*y*y equals x.
How do you do that?
I actually expect that many do not know that. I didn’t before I studied high-level math in college.
Here we go.
print(27**(1/3))
Ah, you see. You lift to the power of one third. It will print 3, as 3*3*3 is 27.
#10 Get the absolute value of a number
Again a great built-in function to know.
I often need the absolute values of a number. This can be achieved by using abs().
a = -27
print(abs(a))
This will print 27.
#11 Round a number to n digits
If you’ve been working with floats, you know the pain of endless long digits.
Another great built-in function in Python will help you here.
pi = 3.1415
pi_two_digits = round(pi, 2)
print(pi_two_digits)
This will print 3.14.
#12 Create a list of numbers in specific range
I actually used this one all the time before. And I loved to use it with Python loops.
Let’s see what it is.
my_list = list(range(7, 23))
print(my_list)
This will generate the following list.
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
If you need to iterate a specific number of times.
for i in range(100):
print(i)
This will iterate from 0 to 99 and print the values.
#13 Calculate the average of a list
Now does the use of this need to be explained?
You have a list of numbers, you need the average of the numbers in the list?
One line of Python will do it for you.
l = [1, 2, 3, 4, 5]
average = sum(l)/len(l)
print(average)
It will print 3.0, as it is the average of the list.
#14 If-else assignment
First I wasn’t really fan of this one. But when you keep it simple, it is useful. The key is not to have complex checks to keep the readability good.
x = 19
v = 42 if x < 10 else 27
print(v)
This will output 27, as x is greater than 10. Try it with x = 5 and see it will print 42.
#15 Flatten a list of lists
First of all, what does does flatten a list of list mean?
Given a list of lists.
l = [[1,2], [4, 6], [8, 10]]
How do you get a list of all the numbers, like this one?
[1, 2, 4, 6, 8, 10]
You do that as follows.
flat = [i for j in l for i in j]
(Bonus) Check if word is a palindrome
What does it mean that a word is a palindrome?
That it is spelled the same from back and front.
The typical example is racecar .
See, it is identical spelled backwards and forwards.
How can you check that a word is a palindrome? Obviously in one line of code? Yes, you should be able to do that now after this list.
Extra bonus: This is a typical job interview question. Be sure to nail this one and impress them.
Here we go.
s = 'racecar'
print(s == s[::-1])
This will print True as it is a palindrome.
s = 'palindrome'
print(s == s[::-1])
This will print False, as it is not a palindrome (except the string is palindrome).
How does it work?
Well, s[::-1] is the reverse of s. If the reverse of s equals s, then it must be a palindrome.
Want to learn more?
f you are hooked on learning Python I will suggest you follow my beginners course on Python.
It is well structured and has focus on you as a learner.
I suggest you break it down as explained in #1.
- Day 1: See lesson with new concepts – take notes.
- Day 2: Recap lesson (either from notes or video) – then see introduction to project. Try to solve the project and stop when you get stuck.
- Day 3: Possibly recap lesson again, then continue with project. If you are really stuck – see solution.
Then continue that pattern for each lesson.
The course is structured with the following resources to improve your learning experience.
- 17 video lessons teaching you everything you need to know to get started with Python.
- 34 Jupyter Notebooks with lesson code and projects.
- A FREE 70+ pages eBook with all the learnings from the lessons.
Python for Finance: Unlock Financial Freedom and Build Your Dream Life
Discover the key to financial freedom and secure your dream life with Python for Finance!
Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.
Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.
Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.
Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!
Python for Finance a 21 hours course that teaches investing with Python.
Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.
“Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.
