Back to articles list Articles
11 minutes read

10 Native Python One-Liners That Will Blow Your Mind

The essence of Python is simplicity and ease of use. In this article, we will focus on how to write complex operations in a single line in Python.

Python is a general-purpose programming language. It is used for AI and machine learning, web development, data analytics, game development, and financial predictive models, among other things. Almost all modern tech companies, including Google and Netflix, use Python.

Python is a perfect fit as a first programming language. It’s easy to read, write, learn, and understand. Python emphasizes syntax readability by making you write clean code with consistent indentation and without redundancies. It is also powerful, flexible, and easy to use. If you want to start learning Python online, I strongly recommend our Python Basics course. It gives you a solid foundation for beginning your programming journey.

What Are Python One-Liners?

If you’re already working with Python, are you sure the code you write is fully Pythonic? Python developers mostly come from other programming languages, like Java, PHP, or C++. They bring with them traditional ways to write code that could be achieved more elegantly with Python.

Did you know that a lot of complex operations can often be performed in just one line? That is what we call a Python one-liner. In this article, I will demonstrate 10 native Python one-liners that will ensure you write clean and ultra-Pythonic code.

10 Python One-Liners That Will Improve Your Code

1)  Multiple Variable Assignment

Assigning a value to a variable is a fundamental operation in all programming languages. But how about assigning multiple variables? Most programming languages require one operation per assignment, but Python allows you to perform multiple variable assignments in just one operation:

# Traditional way
a = 1
b = "ok"
c = False

# Pythonic way
a, b, c = 1, "ok", False

# Result
print(a, b, c)
# Show: 1 ok False

Note that if you want to perform a successful assignment of multiple variables, the number of variables and values should be the same; otherwise, the system will throw a ValueError.

2)  Variable Swap

Imagine that you have two variables and you want to swap their values. How would you do it? The traditional way to do it is to use a third variable to store the first value temporarily and then perform the swap. It looks ugly and impractical right? Forget that way – it can be done in one line in Python:

# Traditional way
a = 1
b = "ok"

c = a
a = b
b = c

# Pythonic way
a, b = 1, "ok"
a, b = b, a

# Result
print(a, b)
# Shows: ok 1

You can swap more than two variables. Here is an example of a four-variable swap:

# Pythonic way
a, b, c, d = 1, "ok", True, ["i", "j"]
a, b, c, d = c, a, d, b

# Result
print(a, b, c, d)
# Shows: True 1 ["i", "j"] ok

To perform the swap correctly, the number of variables should be the same in the left and right parts of the equality. 

3)  Variable Conditional Assignment

Sometimes, variable assignment is not so simple: you must consider other variables and evaluate them with conditional statements to realize the assignment. Good news! The conditional statement if .. else can be condensed into a single line:

variable = a if condition else b

That means variable will be equal to a if the condition is fulfilled; otherwise, variable will be equal to b. In the following example, the console will print if a number is odd or even in a single line:

x = 3

# Traditional way
if x % 2 == 1:
result = f"{x} is odd"
else:
	result = f"{x} is even"

# Pythonic way
result = f"{x} " + ("is odd" if x % 2 == 1 else "is even")

# Result
print(result)
# Shows: 3 is odd

This example uses f-strings, which allow us to concatenate strings with custom variable values.

4)  Presence of a Value in a List

Have you ever needed to check if a list contains a given value? Some programming languages have built-in functions for this (like the contains() function in Java). In Python, you could do it by looping the list and looking for the given value; even better; you can use the in operator:

pet_list = ["cat", "dog", "parrot"]

# Traditional way
found = False
for item in my_list:
	if item == "cat":
		found = True
		break

# Pythonic way
found = "cat" in pet_list

# Result
print(found)
# Shows: True

Note that the in operator works with any data structure in Python (lists, sets, tuples, and dictionaries). Here is an example of using the in operator with a dictionary:

pet_dict = {"cat": "Mitchi", "dog": "Max", "parrot": "Pepe"}
found = "cat" in pet_dict
print(found)
# Shows: True

If you want to know more about data structures, I suggest the article Python Lists, Tuples, and Sets: What’s the Difference? If you want to go further with data structures in Python, I highly recommend taking our Python Data Structures in Practice course. It will teach you how to solve fundamental programming problems with basic data structures.

5)  Operations on Lists

How could you find the largest value in a list? You could loop the list and check each value to find the maximum and store it in a variable. But let’s be honest – this is too much work for something pretty simple. That’s why Python has the built-in function max, which finds the maximum value in a list using just one line of code. (Note that all values of the list should be numeric. Otherwise, a TypeError will be raised.) Here’s an example:

my_list = [1, 2, 3, 4, 5]

# Traditional way
max_value = 0
for value in my_list:
if value > max_value:
max_value = value

# Pythonic way
max_value = max(my_list)

# Result
print(max_value)
# Shows: 5

The good news is that Python also has the built-in functions min and sum to find a list's minimum value and calculate the sum of all values. The max, min, and sum built-in functions work with any iterable variable so that you can use them with any data structure (i.e. lists, sets, tuples, and dictionaries).

6) List Creation with Duplicate Values

Let’s figure out the following case: you want to create a list whose all values are identical. You could do it by creating a loop and adding the values to the list one by one. Although this is a valid approach, you can do it in a significantly simpler way with Python:

size = 10

# Traditional way
my_list = []
for i in range(size):
	my_list.append(0)

# Pythonic way
my_list = [0] * size

# Result
print(my_list)
# Shows: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

The statement [0] * size in the code below performs ten single-value list concatenations. This statement …

my_list = [1, 2] * 5

… will show the following:

[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]

This declaration method also works with tuples; however, it does not work with sets and dictionaries:

my_tuple = (1, 2) * 5
print(my_tuple)
# Shows: (1, 2, 1, 2, 1, 2, 1, 2, 1, 2)

7)  List Creation with Sequential Values

Speaking of lists, what if you want to fill a list with ascending values? This kind of operation can be helpful if, for example, you want to store the index of each element of the list. Following the same logic as the previous example, you could do it by creating a loop and adding the incremented values one by one to the list. Although this is a valid approach, you can do it in a simpler way using the Python list() and range() constructors:

count = 10

# Traditional way
my_list = []
for i in range(count):
	my_list.append(i)

# Pythonic way
my_list = list(range(count))

# Result
print(my_list)
# Shows: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Note that the range() constructor accepts three parameters: the start value (inclusive), the end value (exclusive), and the step value. If not specified, start and step values are respectively 0 and 1 by default. Here is an example of a list composed only of odd values:

# List with odd values
my_list = list(range(1, 10, 2))
print(my_list)
# Shows: [1, 3, 5, 7, 9]

Furthermore, the range() constructor allows negative values. So you could build a list with descending and negative values:

# List with descending values and negative values
my_list = list(range(5, -5, -1))
print(my_list)
# Shows: [5, 4, 3, 2, 1, 0, -1, -2, -3, -4]

This kind of sequential declaration also works with sets and tuples via the set() and tuple() constructors; however, it does not work with dictionaries:

my_set = set(range(count))
my_tuple = tuple(range(count))

# Result
print(my_set)
# Shows: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
print(my_tuple)
# Shows: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

8)  List Creation with a Loop

If you need to perform operations on values before storing them in the list, don’t worry; you can use a one-line loop inside the list declaration. Consider the following example: you need to declare a list containing the ascending square values of a given number.

count = 4

# Traditional way
my_list = []
for i in range(count):
my_list.append(count**i)

# Pythonic way
my_list = [count**x for x in range(count)]

# Result
print(my_list)
# Shows: [1, 4, 16, 64]

Note that in the example above, we use the power operator “**”. count**x is equivalent to “count to the power of x”.

This kind of looping declaration also works with sets via the set() constructor; however, it does not work with tuples or dictionaries:

my_set = set(count**x for x in range(count))
print(my_set)
# Shows: {1, 4, 16, 64}

9)  List Creation with Conditions

In the previous example, we figured out that we can include a loop in a list declaration. It is also possible to add a condition statement to filter the element we want to store in the list.

Suppose we retrieve a list of database users whose names and ages are stored in tuples:

users = [("Megan", 56),
("Karen", 32),
("Chad", 28),
("Brent", 44)]

Now we want to create a new list containing only the names of young users under 35 years old. The traditional way would be looping the list of users and then appending the user name only if the condition is fulfilled. This is valid, but Python lets us do the same thing in a single line:

# Traditional way
young_users = []
for user in users:
	if (user[1] < 35):
		young_users.append(user[0])

# Pythonic way
young_users = [x for x, y in users if y < 35]

# Result
print(young_users)
# ["Karen", "Chad"]

This kind of conditional declaration also works with sets, but it does not work with tuples or dictionaries:

young_users = {x for x, y in users if y < 35}
print(young_users)
# {"Karen", "Chad"}

10)  Reading a File Line by Line

Now suppose we need to read a file line by line, remove each line’s leading and trailing whitespaces, add a line number as a prefix to each line, and finally store the data in a list. Here are the traditional and the Pythonic ways:

# Traditional way
lines = []
with open(filename) as file:
for count, line in enumerate(file):
lines.append(f"Line {count + 1}: " + line.strip())

# Pythonic way
with open(filename) as file:
lines = [f"Line {count + 1}: " + line.strip() for count, line in enumerate(file)]

Well, there are two lines in the Python code, but it’s still pretty cool. You could write it in one line, but the Python PEP 8 guidelines discourage it.

# Discouraged
with open(filename) as file: lines = [f"Line {count + 1}: " + line.strip() for count, line in enumerate(file)]

If you are worried about closing the file, please don’t! The with statement automatically closes the file after reading it, as mentioned in the Python documentation.

Like the previous example, this kind of declaration also works with sets but not with tuples or dictionaries:

with open(filename) as file:
lines = {f"Line {count + 1}: " + line.strip() for count, line in enumerate(file)}

Learn Python Today!

Did you like these native Python one-liners? Are you interested in learning more about such an efficient coding language? Then I strongly recommend you check out the Learn Programming with Python track on LearnPython.com. Who knows – you may even decide to make Python programming your career!

Python offers a large array of professional options that range from software developer to ethical hacker. According to ZipRecruiter, the average salary for a Python developer in the United States is $111,601 per year. Not bad! I recommend this article on Python jobs and salaries if you want to see a detailed salary analysis by career path.

So, what are you waiting for? Learn Python today!