When we start learning Python, we usually give priority to writing code that does the work, rather than focusing on readability, simplicity, and efficiency.
This is perfectly fine, but there are ways to shorten our Python code without ignoring readability. One-line Python code, as long as we use them correctly, gives us a good balance of simplicity and readability!
Here are nine single-line codes that any student learning Python should know. Let's take a look.
1. If-Else statement
The if-else statement is one of the first statements we learned in Python and is used to execute the true and false parts of a given condition.
We often use this statement, but do you know it can be simplified to a single line of code? In many cases, it's perfectly possible to put if and else statements 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 new list from an existing list
Lists are a common way to store data, but did you know that a new list can be created from an existing list in just one line of code?
Yes, it is called list derivation, and it provides a short phrase for creating lists based on the values of existing lists, which are more compact than functions and loops used to make lists.
Here is the grammar
[expression for item in list]
Let's take an example
words = ['united states', 'brazil', 'united kingdom'] capitalized = [word.title() for word in words] >>> capitalized ['United States', 'Brazil', 'United Kingdom']
The code above really looks better! But keep in mind that we should keep the code user-friendly, so it is not recommended to write long list derivations in one line of code.
3. Dictionary Derivation
Similar to list derivation, there are dictionary derivations in Python. Dictionary derivation provides a short syntax for creating a dictionary in one line of code.
Here is the grammar
{key: value for key, value in iterable}
A chestnut
dict_numbers = {x:x*x for x in range(1,6) } >>> dict_numbers {1: 1, 2: 4, 3: 9, 4: 16, 5:25}
4. Merge Dictionaries
There are many ways to merge dictionaries. We can use the update() method, the merge() operator, or even dictionary derivation.
But there is a simpler way to merge dictionaries in Python by using the unpacking operator**. We just need to add** before each dictionary we want to combine and use an extra 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}
When we apply the ** operator to a dictionary, both expand its contents and merge them to create a new dictionary.
5. Remove duplicates from the list
Sometimes we need to make sure there are no duplicate values in the list, and although there is no easy way to handle them, we can use set to eliminate duplicates.
set is an unordered collection in which each element is unique. This means that if we turn the list into a collection, we can quickly delete duplicates. Then we just need to convert the collection back into a list.
Let's take a look at a basic example to master 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. Assigning values to multiple variables in a row
Whenever we need to allocate more than one variable, we can allocate them on a single line in Python instead of on a line-by-line basis (even from different types of variables).
a, b, c = 1, "abc", True >>> a 1 >>> b 'abc' >>> c True
It's very concise, but it's important to note that the more variables we allocate, the greater the chance we will allocate them to the wrong values, double-edged sword ~
7. Filter values from lists
Suppose we want to filter some values from the list, there are many ways to do this, but one simple way is to use the filter() function.
This is the syntax of the filter function:
filter(function, iterable)
It would be better if we added a lambda function to the filter function!
Let's master it by filtering even numbers from the list
my_list = [10, 11, 12, 13, 14, 15] >>> list(filter(lambda x: x%2 == 0, my_list )) [10, 12, 14]
8. Key Sort Dictionary
Sorting dictionaries is not as easy as sorting lists - we cannot sort dictionaries using sort() or sorted() as lists do.
But we can combine dictionary derivation with the sorted() function to sort dictionaries by keys.
In the following example, we will sort the dictionary by product name.
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}
9. Sort dictionaries by value
Similar to sorting dictionaries by keys, we need to sort dictionaries by value using the sorted() function and list derivation, but we also need to add a lambda function.
First let's look at all the parameters of the sorted() function
sorted(iterable, key=None, reverse=False)
To sort dictionaries by value, we need to use the key parameter. This parameter accepts a function that is used as the key for sorting comparisons. Here, we can use the lambda function to make things easier.
Suppose we have a dictionary of population values that we want to sort by value
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 a dictionary and derive
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}
Okay, that's all we've shared today. If you like, just give it a compliment.
Now I invite you to join our Software Testing Learning Exchange Group: [746506216], Note "Join the Group". You can discuss Exchange Software Testing, learn software testing techniques, interviews and other aspects of software testing together. There will also be free live classes and more testing skills. We will work together to advance Python automated testing/test development and move to a high-paid road.
Partners who like software testing, if my blog is helpful to you and if you like my blog content, please "compliment", "comment", "collection" one click three times!