Python is a powerful and versatile programming language that is known for its readability and simplicity. One way to make your Python code even more concise and efficient is to use one-liners, which are single lines of code that perform a specific task. In this post, we’ll explore ten Python one-liners that can save you time and make your code more readable. Whether you’re a beginner or an experienced Python developer, these one-liners are sure to come in handy in your projects. So let’s get started!
- Swapping variables
a, b = b, a
This one-liner allows you to swap the values of two variables a
and b
in a single line of code.
2. Merging two dictionaries
d1.update(d2)
This one-liner merges the key-value pairs of the dictionary d2
into the dictionary d1
.
3. Finding the intersection of two lists
set(list1) & set(list2)
This one-liner returns a set containing the elements that are present in both list1
and list2
.
4. Reversing a string
string[::-1]
This one-liner returns a new string that is the reverse of the original string.
5. Sorting a dictionary by value
sorted(d.items(), key=lambda x: x[1])
This one-liner returns a new list of the key-value pairs in the dictionary d
, sorted by value.
6. Flattening a list of lists
[item for sublist in list_of_lists for item in sublist]
This one-liner flattens a list of lists into a single list by iterating over the sub lists and appending each item to the resulting list
7. Removing duplicates from a list
list(set(items))
This one-liner converts the list items
to a set, which removes any duplicates, and then converts it back to a list.
8. Counting the frequency of elements in a list
from collections import Counter
Counter(items)
This one-liner uses the Counter
class from the collections
module to count the frequency of each element in the list items
.
9. Zipping and unzipping lists
zipped = zip(list1, list2)
unzipped = zip(*zipped)
The zip
function combines the elements of two or more lists into a single list of tuples. The *
operator is used to "unzip" a list of tuples back into separate lists.
10. Generating a range of numbers
range(start, stop, step)
This one-liner generates a sequence of numbers from start
to stop
, incrementing by step
each time.