avatarArtturi Jalli

Summary

This article provides 15 useful Python shorthands to improve coding skills and write more readable and professional code.

Abstract

The article "15 Useful Python Shorthands" offers tips and tricks for Python programmers to enhance their coding skills. It covers various topics such as one-liner if-else statements, one-liner functions, swapping variables without a helper variable, chaining comparisons, one-liner for-loops, lambda expressions, repeating strings without loops, reversing a string, simplifying if-statement conditions, finding the most frequent element in a list, tearing values to variables from a list, using F-strings, simulating a coin toss, joining a list of strings into one string, and creating an enumeration. Each tip is explained with examples and code snippets to help readers understand and implement them in their own projects.

Bullet points

  • One-liner if-else statements
  • One-liner functions
  • Swapping variables without a helper variable
  • Chaining comparisons
  • One-liner for-loops
  • Lambda expressions
  • Repeating strings without loops
  • Reversing a string
  • Simplifying if-statement conditions
  • Finding the most frequent element in a list
  • Tearing values to variables from a list
  • Using F-strings
  • Simulating a coin toss
  • Joining a list of strings into one string
  • Creating an enumeration

15 Useful Python Shorthands

Write less to achieve more.

Photo by Martin Shreder on Unsplash

Python is a popular programming language that is easy to learn and nice to work with. It is commonly used in data science, machine learning, artificial intelligence, and so on.

In this guide, you learn 15 simple tips to take your Python skills to the next level by writing more readable and professional code.

Let’s get right into it!

1. One-Liner If-Else

Sometimes when an if-else expression is simple enough, it might actually be cleaner to write it as a one-liner:

2. One-Liner Functions

As with the previous example, sometimes you also might want to give the function definition in one line:

3. Swap Two Variables without a Helper Variable

This is a classic interview question: How can you swap two variables without using a third helper variable? The answer is simple:

4. Chain Comparisons

This one is pretty neat. Instead of doing this:

x > 0 and x < 200

You can write it down just like you would do in a math’s class:

0 < x < 200

5. One-Liner For-Loops

You can use what is called a list comprehension to loop through a list neatly with one line of code. For example, let’s square each number in a list of numbers:

>>> numbers = [1, 2, 3, 4, 5]
>>> [num * num for num in numbers]
[1, 4, 9, 16, 25]

Using comprehensions is not restricted to lists only. You can use a similar syntax with dictionaries, sets, and generators too. For instance, let’s use dictionary comprehension to square values of a dictionary:

>>> dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> { key: num * num for (key, num) in dict1.items() }
{'a': 1, 'b': 4, 'c': 9, 'd': 16}

6. Lambda Expressions

In Python, a lambda function is just a nameless function. It can take any number of arguments but can only have a single expression. For instance, here is a lambda that multiplies a number by three:

>>> lambda x : x * 3

Lambdas are useful when you need the functionality for a short period of time. A practical example is filtering a list. Python’s built-in filter method takes two parameters:

  • A filtering function (this is a lambda function)
  • A list to be filtered

As an example, let’s filter even numbers from a list by passing a lambda function into the filter() method to check if a number is even:

>>> numbers = [1, 2, 3, 4, 5, 6]
>>> list(filter(lambda x : x % 2 == 0 , numbers))
[2, 4, 6]

7. Repeat Strings without Using Loops

You can simply multiply a string by an integer to repeat it as many times as you prefer:

>>> "word" * 4
wordwordwordword

8. Reverse a String

>>> sentence = "This is just a test"
>>> sentence[::-1]
tset a tsuj si sihT

9. Simplify If-Statement Conditions

Would you agree that this looks pretty bad, even though there’s nothing wrong with it?

>>> if n == 0 or n == 1 or n == 2 or n == 3 or n == 4 or n == 5:

Instead of this mess, you can make it look better by doing this:

>>> if n in [0, 1, 2, 3, 4, 5]

10. Find the Most Frequent Element of a List

>>> nums = [2, 2, 6, 2, 2, 3, 4, 2, 113, 2, 1]
>>> max(set(nums), key = nums.count)
2

11. Tear Values to Variables from a List

You can easily destructure list elements into separate variables. For example:

>>> arr = [1, 2, 3]
>>> a, b, c = arr
>>> print(a, b, c)
1 2 3

12. F-Strings

With Python 3.6 and later, you can use F-Strings to embed expressions inside strings. As an example:

13. Simulate Coin Toss

You can use the choice() method of the random module to pick random elements from a list.

>>> import random
>>> random.choice(['Head',"Tail"])
Head

14. Join a List of Strings to One String

You can neatly join a list of strings together using the join() method of a string.

>>> words = ["This", "is", "a", "Test"]
>>> " ".join(words)
This is a Test

Feel free to check out more string methods in Python.

15. Create an Enumeration

Often times it is bad practice to write hard-coded strings. For instance, here the direction is compared to arbitrary strings that are not guaranteed to be spelled correctly:

This is where enumerations come in handy. Enumerations define a common “type” for a group of related values. Let’s put this idea into use by creating an enumeration for the directions:

Now you can use this enumeration in place of arbitrary strings as the directions:

Feel free to read a complete article on Python enumerations:

Conclusion

Thanks for reading! I hope you learned something new today.

I’d love to join your LinkedIn network.

Feel free to connect Artturi Jalli.

Python
Data Science
Programming
Software Development
Education
Recommended from ReadMedium