Looking to write elegant and Pythonic code? Here’s a list of useful Python one-liners to perform simple tasks.
If you’re a beginner Python programmer, you’ll spend time understanding basic data structures like lists and strings. And some operations on these data structures can be achieved through concise one-line code snippets.
As a programmer, you should prioritize readability and maintainability over making code shorter. But Python it’s easy to come up with one-liners that follow good coding practices.
In this article, we’ll focus on one-liners for simple list and string-processing tasks in Python.
Let’s get started!
Generate a List of Numbers
The simplest way to generate a list of numbers is by using the range()
function. The range()
function returns a range object which you can cast into a list. Using range(num)
will give the sequence 0, 1, 2,.., num-1.
>>> nums = list(range(10))
>>> nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
More on using the
range()
functionYou can also use the
range()
function along with an optional step value. Sorange (start, end, step)
will give the sequence start, start + step, start + 2*step, and so on. The last value will be start + k*step such that (start + k*step) < end and (start + (k+1)*step) > end.
Find the Max and Min Values in a List
You can use the built-in max and min functions to compute the maximum and minimum elements in a list, respectively.
>>> min_elt, max_elt = min(nums), max(nums)
>>> min_elt
0
>>> max_elt
9
📑 Note on Multiple Assignment
Notice that we’ve assigned values to both
min_elt
andmax_elt
in a single assignment statement. Python supports such multiple assignment. And this can be helpful when unpacking iterables and assigning values to multiple variables at the same time.
Remove Duplicates From a List

Another common operation is removing duplicates from Python lists. This is necessary when you need to work with only the unique values. The simplest way to do so is to convert the list to a set.
A set is a built-in data structure whose elements are all unique and hashable.
>>> nums1 = [2,4,7,9,7,10]
In nums1
, the element 7 occurs twice. Casting it into a set will remove the duplicate (here, 7) leaving us with a list of unique values.
Because we still need to work with the list, we’ll convert the set back to a list. This operation can be accomplished with the following line of code:
>>> nums1 = list(set(nums1))
>>> nums1
[2, 4, 7, 9, 10]
📒 To learn more about other techniques to remove duplicates from Python lists, check out this guide.
Count Occurrences in a List
To count the number of times an element occurs in a list, you can use the built-in count()
method. list.count(elt)
returns the number of times elt
occurs in the list
.
>>> nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Here, 7 occurs once in the nums
list, so the count()
method returns 1.
>>> nums.count(7)
1
Check if All Elements in the List Satisfy a Condition
To check if all elements in a list satisfy a condition, you can use Python’s built-in all()
function.
The all()
function takes in an iterable as the argument and returns True if all the elements in the iterable evaluate to True
(or are truthy).
Here, we’d like to check if all elements in the nums2
list are odd.
>>> nums2 = [3,4,7,11,21,67,12]
We can use list comprehension to construct a list of Booleans and we can pass in that list as the argument to the all()
function.
Here, num%2!=0
will be False
for the elements 4 and 12 which are even. Therefore, the list of Booleans constructed using list comprehension expression contains False
(and all(list)
returns False
).
>>> all([num%2!=0 for num in nums2])
False
💡 It’s important to note that
all([])
(all(any-empty-iterable
) returnsTrue
.
Check if Any Element in the List Satisfies a Condition
To check if any element in a list satisfies a condition, you can use the any()
function. any(some-list)
returns True
if at least one element evaluates to True
.
>>> nums2 = [3,4,7,11,21,67,12]
As with the previous example, we use list comprehension to get a list of Booleans. The nums
list contains even numbers. So the any()
function returns True
.
>>> any([num%2 for num in nums2])
True
Reverse a String
In Python, strings are immutable, so when you want to reverse a string, you can only obtain a reversed copy of the string. There are two common approaches—both of which can be written as Python one-liners—that use string slicing and built-in functions.
Using String Slicing
String slicing with negative values of step returns a slice of the string starting from the end. The syntax is string[start:stop:step]
. So what does setting step of -1 and ignoring the start and stop indices return?
It returns a copy of the string, starting from the end of the string—including every character.
>>> str1[::-1]
'olleh'
Using the reversed() Function
The built-in reversed()
function returns a reverse iterator over a sequence.
>>> reversed(str1)
<reversed object at 0x008BAF70>
>>> for char in str1:
... print(char)
...
h
e
l
l
o
You can use it in conjunction with the join()
method, as shown:
>>> ''.join(reversed(str1))
'olleh'
Convert a String to a List of Characters

Suppose we’d like to split a string to a list of characters. We can do so using list comprehension expression.
>>> str1 = 'hello'
List comprehensions are one of the most powerful one-liners in Python.
📒 Learn more about list comprehensions in Python.
We loop through the string and collect each character.
>>> chars = [char for char in str1]
>>> chars
['h', 'e', 'l', 'l', 'o']
To split a string into a list of characters, you can also use the list()
constructor:
>>> str1 = 'hello'
>>> chars = list(str1)
>>> chars
['h', 'e', 'l', 'l', 'o']
To split a longer string into a list of strings on every occurrence of whitespace, you can use the split()
method.
>>> str2 = 'hello world'
>>> str2.split()
['hello', 'world']
Extract Digits From a String
We’ve already seen how to use list comprehension to split a string into a list of characters. In that example, we collected all the characters by looping through the string.
Here, we need to loop through the string and collect only the digits. So how do we do that?
- We can set the filtering condition in the list comprehension expression using the
isdigit()
method. c.isdigit()
returnsTrue
ifc
is a digit; else it returnsFalse
.
>>> str3 = 'python3'
>>> digits = [c for c in str3 if c.isdigit()]
>>> digits
['3']
Check if a String Starts with a Specific Substring
To check if a string starts with a specific substring, you can use the startswith()
string method. str1.startswith(substring)
returns True
if str1
starts with substring
. Otherwise, it returns False
.
Here are a couple of examples:
>>> str4 = 'coding'
>>> str4.startswith('co')
True
>>> str5 = 'python'
>>> str5.startswith('co')
False
Check if a String Ends with a Specific Substring
As you might have guessed, to check if a string ends with a given substring, you can use the endswith()
method.
>>> str5 = 'python'
>>> str5.endswith('on')
True
We can as well use the string method in inside a list comprehension expression to get ends_with
, a list of Booleans.
>>> strs = ['python','neon','nano','silicon']
>>> ends_with = [str.endswith('on') for str in strs]
>>> ends_with
[True, True, False, True]
Join Elements of a List Into a String
We’ve already seen how to split a string into a list of characters. Now how do we do the inverse operation of joining the elements of a list into a string?
To do this, you can use the join()
string method with the syntax: separator.join(some-list)
.
We’d only like to combine the elements in the list into a single string; we do not need any separator. So we set the separator to an empty string.
>>> list_1 = ['p','y','t','h','o','n','3']
>>> ''.join(list_1)
'python3'
Create a Python Dictionary

Just the way list comprehensions can help us construct new lists from existing iterables, dictionary comprehensions can help us construct new dictionaries from existing iterables.
Python dictionary comprehensions are powerful one-liners that can help construct help create a dictionary on the fly.
Here, we have names
which is a list of strings.
>>> names = ['Joe','Amy','Jake','Florence']
We create names_d
, a dictionary containing name strings as the keys and the lengths of the strings as the value.
>>> names_d = {name:len(name) for name in names}
>>> names_d
{'Joe': 3, 'Amy': 3, 'Jake': 4, 'Florence': 8}
Conditionally Assign Values to Variables
Sometimes you may need to assign values to variables depending on a specific condition.
For example, you might read in user input, say, the age of the individual. And depending on the input value, you can decide whether or not they are allowed to attend a party.
To do this conditional assignment in Python, you can write the following one-liner using the ternary operator.
>>> age = 21
>>> allowed = True if age >= 18 else False
>>> allowed
True
🔖 Learn more about the ternary operator in Python.
Generate All Permutations
Permutation refers to a possible arrangement of elements in a group. If there are n unique elements in a group, there are n! possible ways to arrange them—and hence, n! permutations.
Let’s use the following list letters
:
>>> letters = ['a','b','c']
You can use permutations
from the itertools module to generate all possible permutations of the given iterable.
>>> letters_p = permutations(letters)
>>> letters_p
<itertools.permutations object at 0x0127AF50>
As seen, using permutations(iterable)
returns a permutation object we can loop through using a for loop:
>>> for p in letters_p:
... print(p)
...
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
But we can rewrite it as a one-line expression by casting the permutation object to a list:
>>> letters_p = list(permutations(letters))
>>> letters_p
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
Here, there are three unique elements, and there are 3!=6 possible permutations.
Generate Subsets of a List
Sometimes you may need to construct all possible subsets of a particular size from a list or other iterables. Let’s use the letters
list and get all sublists of size 2.
To do so, we can use combinations
from itertools
module, like so:
>>> from itertools import combinations
>>> letters_2 = list(combinations(letters,2))
>>> letters_2
[('a', 'b'), ('a', 'c'), ('b', 'c')]
Conclusion
In this tutorial, we looked at useful Python one-liners to perform common operations on lists and strings. We also learned one-liners like Python list and dictionary comprehensions and how to use them in conjunction with built-in functions to perform the desired tasks.
As a next step, check out this list of beginner-friendly Python projects.
-
Bala Priya is a developer and technical writer from India with over three years of experience in the technical content writing space. She shares her learning with the developer community by authoring tech tutorials, how-to guides, and more…. read more