10 Awesome Pythonic One-Liners Explained
Andreas

Andreas @devmount

About: freelancing software engineer. javascript. php. python. css. husband. dad². guitarero. climber. retrogamer.

Location:
Berlin, Germany
Joined:
Aug 26, 2017

10 Awesome Pythonic One-Liners Explained

Publish Date: Jul 29 '20
167 35

Since I wrote my first lines of code in Python, I was fascinated by its simplicity, excellent readability and its popular one-liners in particular. In the following, I want to present and explain some of these one-liners - maybe there are a few you didn't already know and are useful for your next Python project.

1. Swap two variables

# a = 1; b = 2
a, b = b, a
# print(a,b) >> 2 1
Enter fullscreen mode Exit fullscreen mode

Let's start with a classic: swapping the values of variables by simply swapping positions on assignment - the most intuitive way in my opinion. No need to use a temporary variable. It even works with more than two variables.

2. Multiple variable assignment

a, b, *c = [1,2,3,4,5]
# print(a,b,c) >> 1 2 [3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Swapping variables is actually a special case of Pythons ability to assign multiple variables at once. Here you can use it to assign list elements to the given variables, which is also called unpacking. The * will do packing the remaining values again, which results in a sublist for c. It even works for every other position of * (e.g. the beginning or middle part of the list).

3. Sum over every second element of a list

# a = [1,2,3,4,5,6]
s = sum(a[1::2])
# print(s) >> 12
Enter fullscreen mode Exit fullscreen mode

No need for a special reduce function here, sum just adds the items of every given iterable. The extended slicing syntax [::] is used here to return every second element. You can read it as [start : stop : step], so [1::2] translates to start with the element of index 1 (second element), don't stop until the list ends (no argument given for second parameter) and always take 2 steps.

4. Delete multiple elements

# a = [1,2,3,4,5]
del a[::2]
# print(a) >> [2, 4]
Enter fullscreen mode Exit fullscreen mode

The extended slicing syntax can also be used to delete multiple list elements at once.

5. Read file into array of lines

c = [line.strip() for line in open('file.txt')]
# print(c) >> ['test1', 'test2', 'test3', 'test4']
Enter fullscreen mode Exit fullscreen mode

With Pythons inline for loop you can easily read a file into an array of lines. The strip() is needed to remove the trailing line breaks. If you want to keep them or they don't matter to you, you can use an even shorter one-liner:

c = list(open('file.txt'))
# print(c) >> ['test1\n', 'test2\n', 'test3\n', 'test4\n']
Enter fullscreen mode Exit fullscreen mode

It's really that simple to read a file in Python. Side note: you can also use the readlines() method if you like.

6. Write string to file

with open('file.txt', 'a') as f: f.write('hello world')
# print(list(open('file.txt'))) >> ['test1\n', 'test2\n', 'test3\n', 'test4\n', 'hello world']
Enter fullscreen mode Exit fullscreen mode

With the help of the with statement, you can directly write content to a file. Make sure to use the correct mode to open the file (here 'a' for appending content).

7. List creation

l = [('Hi ' + x) for x in ['Alice', 'Bob', 'Pete']]
# print(l) >> ['Hi Alice', 'Hi Bob', 'Hi Pete']
Enter fullscreen mode Exit fullscreen mode

Lists can be dynamically created from other lists with the inline for loop. You can directly modify the values, like string concatenation in this example.

8. List mapping

l = list(map(int, ['1', '2', '3']))
# print(l) >> [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

You can also use Pythons map() function to cast every list element to another type.

9. Set creation

squares = { x**2 for x in range(6) if x < 4 }
# print(squares) >> {0, 1, 4, 9}
Enter fullscreen mode Exit fullscreen mode

It's similar with sets. In addition to the inline for loop, you can even directly append a condition!

10. Palindrome check

# phrase = 'deleveled'
isPalindrome = phrase == phrase[::-1]
# print(isPalindrome) >> true
Enter fullscreen mode Exit fullscreen mode

A palindrome is a series of characters that read the same both forwards and backwards. Normally you would need some looping and conditions to check, if a given string is a palindrome. In Python, you just compare the string with its reverse string. Instead of using the slicing operator [::-1], you can also use the reverse() function to reverse the string.

Bonus: The Zen of Python

import this
Enter fullscreen mode Exit fullscreen mode

Well, this one needs no explanation. Just try it yourself by simply entering it in your Python shell 😊🎉

Wrap it up

We've seen some (admittedly simple) examples of Python one-liners, that are powerful and well readable at the same time. Maybe you know another helpful one-liner? Share it with us in the comments!


Published: 29th July 2020

Comments 35 total

  • Waylon Walker
    Waylon WalkerJul 29, 2020

    Great article, I really like the idea of the easily consumable content. I may think of how I can do something like this in my own way 😉


    I am surprised that you made it through 10 one-liners with no ternary statement.

    >>> 'Hi ' if 'Bob' in ['Alice', 'Bob', 'Pete'] else 'Goodbye'
    'Hi'
    
    • Andreas
      AndreasJul 29, 2020

      My pleasure 😊

      I didn't cover everything on purpose, but I totally forgot about the ternary statement 😅 So thank you for this addition! 👍🏻

  • Gabrielle
    GabrielleJul 29, 2020

    I didn't know most of these tricks. Good article and great clarity 😁

    • Andreas
      AndreasJul 29, 2020

      Awesome, thank you! I'm glad it was helpful 😊

  • Ravi
    RaviJul 29, 2020

    Nice Article. 10th one is enough to explain you why people love Python so much, for doing similar thing in other languages would require you to write a numerous lines of code :)

    • Andreas
      AndreasJul 30, 2020

      I'm glad you like it 😊 and it's true: I love Python, because its concepts are so well thought through 👌🏻

  • АнонимJul 30, 2020

    [deleted]

    • Andreas
      AndreasJul 30, 2020

      Good point, thank you for this clarification!

      PS: For the sake of correctness: it's readlines() without the underscore, isn't it?

      • Mark Blakeney
        Mark BlakeneyJul 30, 2020

        Sorry, I was actually incorrect. I thought readlines() was a generator but apparently it isn't so I deleted my comment.

  • bartszy
    bartszyJul 30, 2020

    Great little article, list/set comprehensions are really awesome !

    • Andreas
      AndreasJul 30, 2020

      Indeed they are! Thanks a lot 😊

  • Andreas
    AndreasJul 30, 2020

    Thanks a lot for encouraging me 🤗

  • Paddy3118
    Paddy3118Jul 30, 2020
    1. Read file into array of lines

    Needs to use rstrip rather than strip if you want to preserve left-hand whitespace in lines.

    • Andreas
      AndreasJul 30, 2020

      Thank you for this addition. In this example I just wanted to strip both ends. To only remove the linebreaks, you have to specify the linebreak character:

      c = [line.rstrip('\n') for line in open('file.txt')]
      
      • Andrew N. Harrington
        Andrew N. HarringtonAug 4, 2020

        If you know the last line of the file does have a '\n', then line[:-1] is shorter.

        • Andreas
          AndreasAug 5, 2020

          Indeed, thank you!

          • Paddy3118
            Paddy3118Aug 7, 2020

            That's a big if. rstrip('\n') or simple rstrip() i find easier to read and less error prone.

  • Paddy3118
    Paddy3118Jul 30, 2020
    1. List mapping

    Best to use list comprehensions instead of map in most cases. For your example:

    l = [int(x) for x in ['1', '2', '3']]
    
    • Andreas
      AndreasJul 30, 2020

      I agree, this increases readability even more! Thank you. Is there any other benefit in using list comprehensions instead of the (specially made for this purpose) map() function?

      • Paddy3118
        Paddy3118Jul 30, 2020

        map returns a map object that you then turn into a list. Readability. There are other comprehensions that follow naturally from list comprehensions to generate, for example, dicts, sets and iterators.

  • DeanWu
    DeanWuAug 5, 2020

    Very good article, can I translate it into Chinese and publish it on my WeChat official account? I will specify the source and author. Hope to get your authorization.

    • Andreas
      AndreasAug 5, 2020

      Hey there, I'm glad you like my article! You are welcome to translate it into Chinese. Please set links to the article, my dev.to profile and my Twitter profile at the beginning and let me know, when you published it ✔️

      • DeanWu
        DeanWuAug 6, 2020

        Thank you for your authorization. This is the link to the translated article. Thanks again!
        mp.weixin.qq.com/s/_K40z0t_z-sSNDC...

        • Andreas
          AndreasAug 6, 2020

          Wow that was fast! 👏🏻 Thanks for the translation and credits. Can you create actual links or are you limited to only show urls as text?

          • DeanWu
            DeanWuAug 11, 2020

            The WeChat link is restricted. This should be a temporary link, which can only be accessed from WeChat. The link will become invalid after a period of time. I put the article on my blog so that everyone can check it at any time. Thank you again for your authorization.
            pylixm.cc/posts/2020-08-05-10-One-...

            • Andreas
              AndreasAug 11, 2020

              I see, thank you! 😎

  • Andres 🐍 in 🇨🇦
    Andres 🐍 in 🇨🇦Aug 5, 2020

    My favs:

    python -m json.tool

    python3 -m http.server

    xD

    • Andreas
      AndreasAug 6, 2020

      Nice, thanks for this addition!
      Can you add some explanation for those who don't know, what these one-liners do?

  • mikaelho
    mikaelhoAug 7, 2020

    This one I sort of learned today:

    ' '.join([v for v in [first, middle, last] if v])

    Concatenate space-separated full name out of parts, where any of the parts may be an empty string or None.

  • Jing Xue
    Jing XueAug 26, 2020

    Nice tips. Although wouldn't you want to use with when reading a file as well? I know it doesn't really matter for short scripts, but it's still a good habit to get into.

  • norway subway
    norway subwayApr 13, 2022

    That is great one. I want to translate it into Urdu and Hindi for my users at techlarapoint.com/bombitup-apk/. Can I please?

    • Andreas
      AndreasApr 14, 2022

      Of course, that would be great! Just provide links to the original article, my Twitter and Github.

    • gufu5
      gufu5Dec 26, 2023

      Absolutely, feel free to translate the content into Urdu and Hindi for your users at techlarapoint.com/bombitup-apk/. It's fantastic that you're making the information accessible to a broader audience. Go ahead and use Vidby to translate the Urdu video into English vidby.com/video-translation/urdu-e... seamlessly. Best of luck with your efforts!

Add comment