Python is incredibly powerful. Here are 10 one-liners that will make you more productive.
1. Swap Two Variables
a, b = b, a
2. List Comprehension
squares = [x**2 for x in range(10)]
3. Read a File
content = open('file.txt').read()
4. Flatten a List
flat = [item for sublist in nested for item in sublist]
5. Dictionary Comprehension
d = {k: v for k, v in zip(keys, values)}
6. Reverse a String
reversed_str = s[::-1]
7. Find Most Common Element
most_common = max(set(lst), key=lst.count)
8. Check if Palindrome
is_palindrome = s == s[::-1]
9. Merge Dictionaries
merged = {**dict1, **dict2}
10. HTTP Request
data = __import__('requests').get('https://api.example.com').json()
Follow me for more Python tips!
Top comments (0)