Back to articles
12 Python One-Liners That Will Make Your Code Shorter (And More Readable)

12 Python One-Liners That Will Make Your Code Shorter (And More Readable)

via Dev.to PythonAlex Spinov

I review a lot of Python code. The difference between a junior and a senior often comes down to knowing these patterns. Here are 12 one-liners I use almost daily. 1. Flatten a List of Lists # Instead of: result = [] for sublist in nested : for item in sublist : result . append ( item ) # One-liner: result = [ item for sublist in nested for item in sublist ] 2. Swap Two Variables a , b = b , a No temp variable needed. Python handles this elegantly. 3. Merge Two Dictionaries merged = { ** dict1 , ** dict2 } # Python 3.9+ merged = dict1 | dict2 If keys overlap, the second dict wins. 4. Read a File Into a List of Lines lines = open ( ' file.txt ' ). read (). splitlines () 5. Find the Most Common Element from collections import Counter most_common = Counter ( my_list ). most_common ( 1 )[ 0 ][ 0 ] Works with strings, numbers, any hashable type. 6. Reverse a String reversed_str = my_string [:: - 1 ] The [::-1] slice works on lists too. 7. Check if All Elements Meet a Condition # Are all scor

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
8 views

Related Articles