10 Powerful Python One-liners
One-liners are usually more time-efficient. Instead of writing a whole block of codes, they achieve the same purposes and help to increase the readability of codes.
For-loops
1. Simple for-loops for Sequence Creation
For example, to create a list for 0 to 5 (inclusive):
lst = []for i in range(5+1): # i starts with 0 and ends with 5
lst.append(i)It could easily be switched with a one-liner:
[i for i in range(5+1)]Or even more concisely, since range(start=0, end, step=1) function itself is used to return a sequence of numbers starting from 0 inclusively (by default), and increments by 1 (by default) to stops before the specified end :
list(range(5+1))All 3 expressions yield the same result: [0, 1, 2, 3, 4, 5]
2. If-else Statement
The program below to match grade based on scores:
if score > 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"One-line implementation:
grade = "A" if score > 90 else "B" if score >= 80 else "C"Syntax:
value1 if condition1 else value2value1 if condition1 else value2 if condition2 else value3
The list could go on for as many condition as there is, but it will affect the readability and the normal if-else block might be more suitable in such cases.
3. For-loops with if Statement
Given a list of scores scores = [70, 75, 83, 90, 96, 100]
grade_A_scores = []for score in scores:
if score >= 90:
grade_A_scores.append(score)print(grade_A_scores)
>>> [90, 96, 100]Or the one-line implementation:
grade_A_scores = [score for score in scores if score >= 90]print(grade_A_scores)
>>> [90, 96, 100]Syntax: [arg for arg in sequence if condition]
4. For loops with if-else statement
Combining section 2 and 3 above, we have the following program:
scores = [70, 75, 83, 90, 96, 100]
grades = []for score in scores:
if score >= 80:
grades.append("Pass")
else:
grades.append("Fail")
print(grades)print(grades)
>>> ['Fail', 'Fail', 'Pass', 'Pass', 'Pass', 'Pass']One-line implementation:
grades = ["Pass" if score >= 80 else "Fail" for score in scores]print(grades)
>>> ['Fail', 'Fail', 'Pass', 'Pass', 'Pass', 'Pass']Syntax: [value1 if condition1 else value2 for arg in sequence] where condition1 is usually an expression of arg
5. Nested For Loop
Sometimes we might work with nested list, and to loop through the elements, we would need a nested for loop: a loop inside the body of an outer loop.
results = [["A", "B", "C", "D", "E"], ["Pass", "Fail"]]for grade_group in results:
for grade in grade_group:
grades.append(grade)print(grades)
>>> ['A', 'B', 'C', 'D', 'E', 'Pass', 'Fail']One-line implementation:
grades = [grade for grade_group in results for grade in grade_group]Both implementations loop through the original list results for different grade_group and then loop through elements in each grade_group to finally gather all the grade elements into a unified list grades .
Syntax: [arg for arg in inner_sequence for inner_sequence in outer_sequence]
Note: The outer loop can contain more than one inner loop. There is no limitation on the chaining of loops, and could always be rewritten as a new one-liner.
Variable Assignment
1. Assign Multiple Variables Simultaneously
Instead of writing each assignment separately on one line each, you could do the following:
start, end, intermediate = 0, 10, 1print(f"start: {start}; end: {end}; intermediate: {intermediate}")
>>> start: 0; end: 10; intermediate: 1And if the variables all have the same values, a chained assignment:
mean = median = mode = 1print(f"mean: {mean}; median: {median}; mode: {mode}")
>>> mean: 1; median: 1; mode: 12. Assign Variables with Arbitrary Length
start, end, *intermediate = [0, 10, 3, 5, 7]print(f"start: {start}; end: {end}; intermediate: {intermediate}")
>>> start: 0; end: 10; intermediate: [3, 5, 7]The asterisk * in front of variable intermediate allows variable number of arguments passed from calling environment. In the above example, the star variable could also take other positions:
*intermediate, start, end = [3, 5, 7, 0, 10]print(f"start: {start}; end: {end}; intermediate: {intermediate}")
>>> start: 0; end: 10; intermediate: [3, 5, 7]Note: there cannot be more than one starred expressions in assignment.
start, *end, *intermediate = [0, 10, 3, 5, 7]print(f"start: {start}; end: {end}; intermediate: {intermediate}")
>>> SyntaxError: multiple starred expressions in assignment3. Value Swapping
To swap the value of 2 variables, instead of using additional variables to store the old values, the re-assignment can be done with one-line implementation.
As shown below, variable maximum and minimum are re-assigned as the opposite of each other simultaneously.
maximum = 10
minimum = 1maximum, minimum = -minimum, -maximumprint(f"maximum: {maximum}; minimum: {minimum}")
>>> maximum: -1; minimum: -10The swapping is not limited to two variables:
a, b, c = 1, 2, 3
print(f"a: {a}; b: {b}; c: {c}")
>>> a: 1; b: 2; c: 3a, b, c = b, c, a
print(f"a: {a}; b: {b}; c: {c}")
>>> a: 2; b: 3; c: 1String/Sequence Slicing
String slicing has similar context as the range() function, it has the syntax iterable[start=0 : end : step=1] in which start is inclusive (0 by default), end is exclusive, and returns the part of the list from start to end at a step size step (1 by default).
Some special cases:
- If
endis not specified: the slicing will stop with the final element
print("one-liner"[4::1])
>>> 'liner'print("one-liner"[::])
>>> 'one-liner'2. If step is negative, the slicing will begin from the last element and work backwards
print("one-liner"[::-1])
>>> 'renil-eno'For the famous problem of Palindrome, which is a word or sentence that reads the same forward or backward: civic, radar, level, etc. To identify whether a variable word in lower case without space or punctuations is a palindrome:
is_palindrome = word == word[::-1]To verify:
word1 = "radar"print(word == word[::-1])
>>> Trueword2 = "palindrome"print(word == word[::-1])
>>> FalseLambda functions
Lambda functions with syntax lambda args: expression is another way to create one-line functions, popularly used for sequence operations including filter , map and reduce as covered in my previous article:






