10 Awesome Pythonic One-Liners Explained
Tags: python, beginners, programming
Published: 2020-07-29 11:18:30

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

```python
# a = 1; b = 2
a, b = b, a
# print(a,b) >> 2 1
```

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

```python
a, b, *c = [1,2,3,4,5]
# print(a,b,c) >> 1 2 [3, 4, 5]
```

Swapping variables is actually a special case of Pythons ability to assign multiple variables at once. Here you can use it to assign [list](https://docs.python.org/3/tutorial/datastructures.html) 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

```python
# a = [1,2,3,4,5,6]
s = sum(a[1::2])
# print(s) >> 12
```

No need for a special reduce function here, [`sum`](https://docs.python.org/3/library/functions.html#sum) just adds the items of every given iterable. The [extended slicing syntax](https://docs.python.org/3/whatsnew/2.3.html#extended-slices) `[::]` 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

```python
# a = [1,2,3,4,5]
del a[::2]
# print(a) >> [2, 4]
```

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


## 5. Read file into array of lines

```python
c = [line.strip() for line in open('file.txt')]
# print(c) >> ['test1', 'test2', 'test3', 'test4']
```

With Pythons inline [for loop](https://docs.python.org/3/tutorial/controlflow.html#for-statements) you can easily read a file into an array of lines. The [`strip()`](https://docs.python.org/3/library/stdtypes.html#str.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:

```python
c = list(open('file.txt'))
# print(c) >> ['test1\n', 'test2\n', 'test3\n', 'test4\n']
```

It's really that simple to read a file in Python. Side note: you can also use the [`readlines()`](https://docs.python.org/3/library/io.html#io.IOBase.readlines) method if you like.


## 6. Write string to file

```python
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']
```

With the help of the `with` statement, you can directly write content to a file. Make sure to use the correct [mode](https://docs.python.org/3/library/io.html#raw-file-i-o) to open the file (here `'a'` for **a**ppending content).


## 7. List creation

```python
l = [('Hi '​ + x) ​for​ x ​in​ [​'Alice'​, ​'Bob'​, ​'Pete'​]]
# print(l) >> ['Hi Alice', 'Hi Bob', 'Hi Pete']
```

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

```python
l = list(map(int, ['1', '2', '3']))
# print(l) >> [1, 2, 3]
```

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


## 9. Set creation

```python
squares = { x**2 for x in range(6) if x < 4 }
# print(squares) >> {0, 1, 4, 9}
```

It's similar with [sets](https://docs.python.org/3/tutorial/datastructures.html#sets). In addition to the inline for loop, you can even directly append a condition!


## 10. Palindrome check

```python
# phrase = 'deleveled'
isPalindrome = phrase == phrase[::-1]
# print(isPalindrome) >> true
```

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

```python
import this
```

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*