30 Key Python Lessons I Wish I Had Discovered Sooner in My Coding Path
The journey of learning Python is unique for each individual, characterized by diverse learning paces and sequences. However, certain concepts, when learned early, can significantly enhance one’s coding proficiency. Here, I share 30 Python concepts that I wish I had grasped earlier in my programming odyssey.

1. Formatted Strings (f-strings)
Early on, I learned to convert non-strings into strings and concatenate using the ‘+’ operator. However, f-strings revolutionized this approach by simplifying concatenation and type management.
Example:
name, age = 'Alice', 30
s = f'My name is {name} and I am {age} years old.'2. Tuple Unpacking
Tuple unpacking allows the assignment of multiple variables in a single line, enhancing code readability and efficiency.
Example:
person = ('Bob', 25, 'Engineer')
name, age, profession = person3. Pretty Printing (pprint)
The pprint function in Python elegantly formats complex data structures for improved readability.
from pprint import pprint
data = {'key1': [1, 2, 3], 'key2': {'innerKey': 100}}
pprint(data)4. List/Dict/Set Comprehension
Comprehensions provide a concise way to construct lists, dictionaries, and sets. They are powerful tools for writing cleaner and more efficient code.
squares = [x**2 for x in range(10)]
squared_dict = {x: x**2 for x in range(10)}
unique_set = {x for x in 'hello world' if x != ' '}**5. *args and kwargs in Functions
These allow functions to accept variable numbers of arguments, offering flexibility in function definitions.
def my_function(*args, **kwargs):
print(args)
print(kwargs)my_function(1, 2, 3, a=4, b=5)6. The Ternary Operator
This operator condenses if-elif-else blocks into a single, elegant line of code.
condition = True
message = "Okay" if condition else "Not okay"7. Magic Methods in Object-Oriented Programming
Magic methods, such as __init__, __str__, and __eq__, define special object behaviors, enhancing the functionality of classes.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}8. if name == ‘main’
This statement is crucial for ensuring code runs only when a script is executed directly, not when imported as a module.
# In script.py
def main():
print("Main function")if __name__ == '__main__':
main()9. Working with Multiple .py Files
Learning to properly import from different Python files is essential in large-scale projects.
helper.py:
def helper_function():
print("Helper function")main.py:
from helper import helper_function
helper_function()10. Lambda Functions
Lambda functions provide a concise way to create anonymous functions, useful in higher-order functions.
adder = lambda x, y: x + y
print(adder(2, 3))11. Data Structures and Algorithms
Proficiency in data structures and algorithms is critical, particularly for coding interviews and software engineering roles.
12. Python’s Built-in Data Structures
Understanding when to use different data structures like lists, tuples, dictionaries, and sets can significantly improve coding efficiency.
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_dict = {'one': 1, 'two': 2}
my_set = {1, 2, 3}13. Pip & requirements.txt
Pip is essential for managing Python libraries, while requirements.txt streamlines the installation of multiple dependencies.
numpy==1.19.2
pandas==1.1.314. Web App/API Building Libraries
Libraries like FastAPI and Flask are key for those aiming to develop front-end and back-end applications.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'15. Type Hinting & Enforcement
Type hinting improves code readability, and tools like mypy enforce these hints, ensuring type consistency.
def add(x: int, y: int) -> int:
return x + y16. Regular Expressions (Regex)
Regex is a powerful tool for string matching and manipulation, invaluable in various programming scenarios.
import re
result = re.findall(r'\d+', 'hello 123 world 456')17. break, continue, and pass
These control statements influence loop behaviors in distinct ways, crucial for flow control in code.
for i in range(5):
if i == 2:
continue
elif i == 4:
break
print(i)18. Truthy and Falsy Values
Understanding how Python evaluates different values in boolean contexts is fundamental for writing effective conditional statements.
if []:
print("This won't print.")
if [1, 2, 3]:
print("This will print.")19. Decorators
Decorators modify a function’s behavior without altering its source code, a concept that initially seems daunting but is incredibly useful.
def my_decorator(func):
def wrapper():
print("Something before function.")
func()
print("Something after function.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()20. Generators & the yield Keyword
Generators provide an efficient way of producing iterable sequences without storing them in memory.
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)21. Introduction to Machine Learning
Starting with concepts like supervised learning and exploring libraries like scikit-learn can demystify machine learning.
22. Exception Handling (try, except, finally)
Properly managing exceptions ensures robust and error-resistant code.
try:
result = 10 / 0
except ZeroDivisionError:
print("Divided by zero!")
finally:
print("This is executed last.")23. Method Chaining
Method chaining allows for more concise and readable code by linking method calls together.
class Chain:
def __init__(self):
self.number = 0
def add(self, value):
self.number += value
return self
def subtract(self, value):
self.number -= value
return self
result = Chain().add(5).subtract(3).number24. Serialization with Pickle
Pickle enables the storage and retrieval of Python objects, a useful feature for data persistence.
import pickle
data = {'a': 1, 'b': 2}
with open('data.pickle', 'wb') as f:
pickle.dump(data, f)25. Debugging Techniques
Effective debugging is crucial for managing larger projects, with tools like IDE debuggers and pdb offering advanced capabilities.
26. Virtual Environments
Virtual environments isolate project dependencies, preventing conflicts and ensuring consistency across development setups.
27. Special Escape Characters
Escape characters like \033[1A and \x1b[2K provide control over console output, enabling dynamic content display.
print("Hello\nWorld") # New line escape character28. Assert, Raise, and Custom Exceptions
Using assert for sanity checks and custom exceptions for specific error handling scenarios is a standard in professional coding.
assert 2 + 2 == 4
if not isinstance(123, str):
raise TypeError("Not a string")29. Multiprocessing
The multiprocessing module allows concurrent execution of functions.
import multiprocessing
def square(n):
return n * n
if __name__ == "__main__":
with multiprocessing.Pool(4) as p:
print(p.map(square, [1, 2, 3, 4]))30. Automated Tests
# test_example.py
def test_example():
assert 1 + 1 == 2
# Run with: pytest test_example.py





