🐍 Notes on Python Shortcuts
✅ 1. Code Shortcuts and Tricks
Task Shortcut Example
Swap Variables One-liner swap a, b = b, a
[x*2 for x in
List Comprehension Create lists in one line
range(5)]
result = 'Yes' if x >
Ternary Operator One-line if-else
0 else 'No'
String Reverse Reverse a string s[::-1]
" ".join(['Hello',
Join List to String Convert list to string
'World'])
Assign multiple values
Multiple Assignment x, y, z = 1, 2, 3
at once
Check Even/Odd Simple check x % 2 == 0 (even)
Get Dictionary Value my_dict.get('key',
Use .get()
with Default 'default')
✅ 2. Useful Built-in Functions
Function Purpose Example
Get length of list, string,
len() len("hello") → 5
etc.
type() Check type of variable type(10) → int
enumerat Get index and value for i, val in
e() from list enumerate(list):
zip() Combine two lists zip(list1, list2)
sorted([3,1,2]) →
sorted() Sort a list
[1,2,3]
set([1,1,2,3]) →
set() Remove duplicates
{1,2,3}
map() Apply function to list map(str, [1, 2, 3])
Filter items based on filter(lambda x: x>0,
filter()
condition nums)
✅ 3. Terminal & Editor Shortcuts (for VS Code / Jupyter)
Shortcut Action
Comment/
Ctrl + /
Uncomment line
Shift +
Run cell in Jupyter
Enter
Alt + ↑ / ↓ Move line up/down
Ctrl + D Select next match
Ctrl + L Select line
Ctrl + Shift Open command
+ P palette
✅ 4. Common Python Idioms (Best Practices)
Use with for file handling:
python
CopyEdit
with open('file.txt') as f:
content = f.read()
Use try-except for error handling:
python
CopyEdit
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
Use if __name__ == "__main__":
Useful when writing scripts to prevent unwanted code from running
when imported.