11 Python One-Liners for Everyday Programming

Programming Image

    Introduction

    Python is a general-purpose programming language that can be used to build projects of any size and gives developers the provisions to write logical and clear code — even for large-scale projects.

    The design philosophy of Python facilitates code readability by enforcing the use of indentation in order to define code blocks explicitly. Just having well-indented code, though, doesn’t necessarily mean that your code is also clear and well-written.

    “Readability counts.” — The Zen of Python

    One of the biggest advantages of Python compared to most other general-purpose programming languages is that it is less verbose. Sacrificing code readability for terseness is never a good idea, though. In many cases, one-liners may cause more harm than good. Trying to reduce the lines of code by putting (complex) statements together will literally kill your code readability.

    Having said that, one-liners can also help keep your code clean and make it look more Pythonic. In this article, we are going to explore a few such cases and see how to use useful one-liners in common programming constructs.

     


     

    Merging Dictionaries

    As of Python 3.9, you can merge dictionaries just by using the | operator:

    >>> dict1 = {'a': 1, 'b': 2}
    >>> dict2 = {'b': 3, 'c': 4, 'd': 5}
    >>> dict1 | dict2
    {'a': 1, 'b': 3, 'c': 4, 'd': 5}

     

    Sorting by an Alternate Key

    Occasionally, we need to sort a list of elements by an alternate key:

    >>> sorted([-5, -1, 2, 3, 4], key=lambda x: abs(x))
    [-1, 2, 3, 4, -5]

     

    Flattening a List of Lists

    Another common use case is when we need to flatten a list of lists. A list comprehension should do the trick:

    >>> nested_lists = [[1, 2], [3, 4, 5], [6]]
    >>> [item for inner_list in nested_lists for item in inner_list]
    [1, 2, 3, 4, 5, 6]

     

    Swapping Variables

    In most programming languages, in order to swap the values of two variables, we would need to introduce a third temporary variable. In Python, this can be achieved in a one-liner:

    >>> a = 10
    >>> b = 20
    >>> a, b = b, a
    >>> a
    20
    >>> b
    10

     

    Assigning Values to Multiple Variables

    As you may have guessed from the previous example, you can also assign values to multiple variables at the same time:

    >>> a, b, c = 10, False, 'Hello World'

     

    Opening Files

    Interacting with resources such as files is a common task in day-to-day programming. A typical use case is when we need to read the contents of a file. Instead of spending time and lines of code to interact with resources and catch errors as shown below, you can use context managers.

    A context manager in Python is an object that defines the runtime context and implements specific functionality before entering and after exiting the context.

    The with statement will open the file and automatically close it after the runtime context terminates (or when something goes wrong):

    with open('file.txt', 'r') as f:
        content = f.readlines()

    The above is equivalent to the more verbose:

    f = open('file.txt', 'r')
    try:
        content = f.readlines()
    finally:
        f.close()

     

    Plural-Format Your Output Strings

    When reporting numbers, we may want to adjust the text message to be either in singular or plural form:

    >>> n_processes = 1
    >>> f"{n_processes} process{' is' if n_processes == 1 else 'es are'} running"
    '1 process is running'
    >>> n_processes = 2
    >>> f"{n_processes} process{' is' if n_processes == 1 else 'es are'} running"
    '2 processes are running'

     

    Lambda Functions

    Lambda functions are single-expression anonymous functions. They can help you write concise inline functions:

    >>> circle_area = lambda r: math.pi * (r ** 2)
    >>> circle_area(10)
    314.1592653589793

     

    Map Function

    We often need to apply a function over a collection of elements, and this is exactly what map() does:

    >>> nums = [1, 2, 3, 4, 5]
    >>> nums_squared = list(map(lambda n: n**2, nums))
    >>> nums_squared
    [1, 4, 9, 16, 25]

     

    Computing the Cumulative Sum

    itertools.accumulate() is a perfect utility if you need to compute the cumulative/running sum of numeric values:

    >>> import itertools
    >>> list(itertools.accumulate([1, 2, 3, 4, 5]))
    [1, 3, 6, 10, 15]

     

    List, Set, and Dictionary Comprehensions

    List, set or dictionary comprehensions can help you write clearer and more Pythonic code. Instead of using traditional for loops, you can instead use a comprehension in just a single line.

    For example, in order to filter a list, you can use the convention below:

    >>> numbers = [1, 2, 3, 4, 5]
    >>> [num for num in numbers if num > 3]
    [4, 5]

     


     

    Conclusion

    Thanks for reading this post, hope you like it.

    0 Comments

    To add a comment, please Signup or Login