15 Most Powerful Python One-liners You Can’t Skip

Image for post
Image for post

Introduction

Ternary operations

x = 1 
y = 2
result = 1 if x > 0 and y > x else -1 print(result)
# 1
#re-assign x to 6 if it is evaluated as False
x = x or 6

Assign values for multiple variables

key, value = "user", "password" print(key, value) #('user', 'password')

Swap variables

key, value = value, key print(key, value) #('password', 'user')

Swap elements in a list

users = ["admin", "anonymous1", "anonymous2"]
users[0], users[2] = users[2], users[0] 
# or users[0], users[-1] = users[-1], users[0]
print(users)
#['anonymous2', 'anonymous1', 'admin']
numbers = list(range(10)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[::2], numbers[1::2] = numbers[1::2], numbers[0::2] print(numbers) 
#[1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

Replace elements in a list

numbers[1::2] = [0]*len(numbers[1::2]) print(numbers) 
#[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]

Generate list with list comprehension

even_nums = [i for i in range(1, 20) if i%2 == 0] print(even_nums) 
#[2, 4, 6, 8, 10, 12, 14, 16, 18]

Create sub list from a list

[i for i in even_nums if i <5] # 2, 4

Manipulating elements in the list

alphabets = [chr(65+i) for i in even_nums] # ['C', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S']
[i.lower() for i in alphabets] #['c', 'e', 'g', 'i', 'k', 'm', 'o', 'q', 's']
list(map(lambda x : chr(65+x), even_nums)) #['C', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S'] list(map(str.lower, alphabets)) #['c', 'e', 'g', 'i', 'k', 'm', 'o', 'q', 's']
import os [f for d in os.walk(".") if not ".ipynb_checkpoints" in d[0] for f in d[2] if f.endswith(".ipynb")]

Flatten a list of sequences

a = [[1,2], [3,4], [5,6,7]]
b = [y for x in a for y in x] print(b) 
#[1, 2, 3, 4, 5, 6, 7]
import itertools list(itertools.chain.from_iterable(a))

Ternary operation with list comprehension

numbers = list(range(10)) [y if i % 2 == 0 else 0 for i, y in enumerate(numbers)] #[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]

Generate a dictionary with dictionary comprehension

even_nums_dict = {chr(65+i):v for i, v in enumerate(even_nums)} #{'A': 2, 'B': 4, 'C': 6, 'D': 8, 'E': 10, 'F': 12, 'G': 14, 'H': 16, 'I': 18}

Generate a set with set comprehension

even_nums_set = {chr(65+i) for i in even_nums} #{'C', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S'}
a = [1,2,2,4,6,7] unique = set(a) print(unique) #{1, 2, 4, 6, 7}

Read file into generator

text = (line.strip() for line in open('response.html', 'r'))

One-liner with Python -c command

python -c "import sys; print(sys.version.split()[0])" #3.7.2
python -c "import os;print(os.getenv('PATH').split(';'))"

Conclusion

Resources and tutorials for python, data science and automation solutions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store