There are a lot of tricks one can use in Python. So-called Python one-liners are one of them. It’s a nice way of shortening the length of the code. However, it’s good to know that sometimes, using the longer version might be the better choice when it comes to readability.
Swapping two variables#
1
2
3
4
|
a = 10
b = 20
a, b = b, a
|
List comprehension#
1
|
squares = [i*i for i in range(20)]
|
Ternary operator#
1
|
my_value = 30 if 5>3 else 50
|
Print only elements (unpacking)#
1
2
|
numbers = [1, 2, 3, 4, 5]
print(*numbers)
|
Days remaining in a year#
1
|
import datetime;print((datetime.date(2023,12,31)-datetime.date.today()).days)
|
Reversing a list/string#
1
2
|
letters = ['a', 'b', 'c', 'd', 'e']
print(letter[::-1])
|
Multiple variable assignments#
1
|
age, city, position = 25, 'London', 'Python developer'
|
Convert number strings into ints#
1
2
|
strs = '1 2 3 4 5 6'
ints = list(map(int, strs.split()))
|
Read all lines of a file to a list#
1
|
values = [line.strip() for line in open('document.txt', 'r')]
|
Start an HTTP server in a terminal#
python -m http.server