Hi!
Before we start with todayās article, I have great news for all of you!
From November 4th to 10th, DataCamp is offering unlimited FREE access to their entire learning platform! Itās the perfect chance to level up your Python, data and AI skills.
This includes:
Access to 510+ courses, career tracks, and certifications
Learn Python, ChatGPT, Power BI, SQL, and more
Land your dream job with data and AI skills
Donāt miss out on this exclusive opportunity. Click here to get free access to Datacamp. In case you donāt know where to start, I recommend you to try this Python Data Fundamentals course.
When we start learning Python, we usually write code that gets the job done without paying attention to the readability of our code and how concise and efficient it is.
Thatās fine, but there are ways to make our Python code shorter without neglecting readability. This is what one-liners are all about (if you use them properly).
Here are 8 one-liners that anyone learning Python should know.
1. IfāāāElse Statement
The if-else statement is one of the first statements we learn in Python. Itās used to execute the true and false parts of a given condition.
We use this statement quite often, but do you know it can be simplified in one line of code? In this case, both the if and else statements would be on the same line.
age = 18
valid = "You're an adult"
invalid = "You're NOT an adult"
print(valid) if age >= 18 else print(invalid)2. Create a list based on existingĀ lists
Lists are a common way to store data, but do you know you can create a new list based on existing lists with just one line of code?
Thatās true! Itās called list comprehension and it offers a short syntax to create a list based on the values of an existing list. List comprehension is more compact than functions and loops for making lists.
Hereās the syntax, weāll use.
[expression for item in list]Hereās an example:
words = ['united states', 'brazil', 'united kingdom']
capitalized = [word.title() for word in words]
>>> capitalized
['United States', 'Brazil', 'United Kingdom']It looks better, isnāt it?
Remember that we should keep the code user-friendly, so donāt write very long list comprehensions in a single line.
3. Dictionary Comprehension
Similar to list comprehension, thereās also dictionary comprehension in Python. The idea is the same. Dictionary comprehension offers a short syntax to create a dictionary in one line of code.
Hereās the syntax, weāll use:
{key: value for key, value in iterable}Hereās an example:
dict_numbers = {x:x*x for x in range(1,6) }
>>> dict_numbers
{1: 1, 2: 4, 3: 9, 4: 16, 5:25}4. Join Dictionaries
There are different ways to join dictionaries. You can use the update() method, merge() operator, and even dictionary comprehension.
That said, thereās a simpler way to join dictionaries in Python. This is by using the unpack operator **. We only need to add the ** in front of each dictionary we wish to combine and use an additional dictionary to store the output.
dict_1 = {'a': 1, 'b': 2}
dict_2 = {'c': 3, 'd': 4}
merged_dict = {**dict_1, **dict_2}
>>> merged_dict
{'a': 1, 'b': 2, 'c': 3, 'd': 4}After we apply the ** operator to the dictionaries, both will expand their content and combine to create a new dictionary.
5. Remove Duplicates in aĀ List
Sometimes we need to make sure there isnāt any duplicate value in our list. Although there isnāt a method that can take care of it easily, you can use sets to get rid of duplicates.
A set is an unordered collection of items where every element is unique. This means that if we turn our list into a set, we can remove duplicates. Then we only need to convert the set into a list again.
Letās see a basic example to get the hang of it.
numbers = [1,1,1,2,2,3,4,5,6,7,7,8,9,9,9]
>>> list(set(numbers))
[1, 2, 3, 4, 5, 6, 7, 8, 9]6. Filter values from aĀ list
Say we want to filter some values from a list. You can use many approaches to do this, but a simple way to do it is by using the filter() function.
Hereās the syntax of the filter function:
filter(function, iterable)If you add a lambda function inside of the filter function, things get even better!
Letās get the hang of it by filtering even numbers from a list.
my_list = [10, 11, 12, 13, 14, 15]
>>> list(filter(lambda x: x%2 == 0, my_list ))
[10, 12, 14]7. Sort dictionary byĀ keys
Sorting dictionaries isnāt as simple as sorting listsāāāwe canāt use either sort() or sorted() to sort dictionaries as we do it with lists.
The good news is that we can combine dictionary comprehension with the sorted() function to sort dictionaries by keys.
Letās have a look. In the example below, weāll sort the dictionaries by the name of the products.
product_prices = {'Z': 9.99, 'Y': 9.99, 'X': 9.99}
>>{key:product_prices[key] for key in sorted(product_prices.keys())}
{'X': 9.99, 'Y': 9.99, 'Z': 9.99}8. Sort dictionary byĀ values
Similarly to sorting dictionaries by keys, we need to use the sorted() function and list comprehension to sort dictionaries by values. But, in addition to that, we also need to add a lambda function.
First, letās see all the parameters that the sorted() function has.
sorted(iterable, key=None, reverse=False)To sort a dictionary by values, we need to use the key parameter. This parameter accepts a function that serves as a key for the sort comparison. Here we can use a lambda function to make things simpler.
Letās say we have a dictionary with population values and we want to sort it by values.
population = {'USA':329.5, 'Brazil': 212.6, 'UK': 67.2}
>>> sorted(population.items(), key=lambda x:x[1])
[('UK', 67.2), ('Brazil', 212.6), ('USA', 329.5)]Now the only thing left is to add dictionary comprehension.
population = {'USA':329.5, 'Brazil': 212.6, 'UK': 67.2}
>>> {k:v for k, v in sorted(population.items(), key=lambda x:x[1])}
{'UK': 67.2, 'Brazil': 212.6, 'USA': 329.5}Thatās it! If you have another one-liner that you use frequently, share it in the comments!



Hey, hope you are well. Iāve a techie mind but never ever wanted to code. My problem is I *have* to know how it works. Thatās why I was the first ever *technical* Project Manager at Cisco. You see, Iāll know *how* it works. A true engineer knows *why* it works - AI black box notwithstanding. Which brings me to my point. You give me the ability to get the how and I really appreciate that. I look forward to more ššš«¶š