AI & Python #30: One-Liners Anyone Learning Python Should Know
Make your Python code concise with these one-liners
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 👍🙏🫶🐇