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.
You can also use the range() function along with an optional step value. So range (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.
Notice that we’ve assigned values to both min_elt and max_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:
📒 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.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Here, 7 occurs once in the nums list, so the count() method returns 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])
💡 It’s important to note that all() (all(any-empty-iterable) returns True.
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])
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.
Using the reversed() Function
The built-in reversed() function returns a reverse iterator over a sequence.
<reversed object at 0x008BAF70>
>>> for char in str1:
You can use it in conjunction with the join() method, as shown:
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.
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.
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