π‘ Top 10 Python Clean Code Practices
1. Use List Comprehensions for Simple Loops
(Replaces verbose
Cluttered Way:
Clean Way:
2. Use
(Avoids manual index tracking with
Cluttered Way:
Clean Way:
3. Use Context Managers for Resources
(Ensures resources like files are properly closed, even if errors occur.)
Cluttered Way:
Clean Way:
4. Use Dictionary
(Prevents
Cluttered Way:
Clean Way:
5. Use F-Strings for Formatting
(More readable and often faster than other string formatting methods.)
Cluttered Way:
Clean Way:
6. Use Unpacking to Swap Variables
(A concise, Pythonic way to swap values without a temporary variable.)
Cluttered Way:
Clean Way:
7. Check for Empty Sequences Correctly
(Leverages Python's "truthiness" for more readable code.)
Cluttered Way:
Clean Way:
8. Use Underscores for Unused Variables
(Signals to other developers that a variable is intentionally ignored.)
Cluttered Way:
Clean Way:
9. Chain Comparison Operators
(Makes numerical range checks more intuitive and readable.)
Cluttered Way:
Clean Way:
10. Return from a Function Early
(Reduces nesting and improves readability by handling edge cases or invalid states first.)
Cluttered Way:
Clean Way:
1. Use List Comprehensions for Simple Loops
(Replaces verbose
for loops for creating lists.)Cluttered Way:
squares = []
for i in range(10):
squares.append(i * i)
Clean Way:
squares = [i * i for i in range(10)]
2. Use
enumerate for Index and Value(Avoids manual index tracking with
range(len(...))).)Cluttered Way:
items = ['a', 'b', 'c']
for i in range(len(items)):
print(i, items[i])
Clean Way:
items = ['a', 'b', 'c']
for i, item in enumerate(items):
print(i, item)
3. Use Context Managers for Resources
(Ensures resources like files are properly closed, even if errors occur.)
Cluttered Way:
f = open('my_file.txt', 'w')
try:
f.write('hello world')
finally:
f.close()Clean Way:
with open('my_file.txt', 'w') as f:
f.write('hello world')4. Use Dictionary
.get() for Safe Key Access(Prevents
KeyError and avoids verbose if key in dict checks.)Cluttered Way:
my_dict = {'name': 'Alice'}
if 'age' in my_dict:
age = my_dict['age']
else:
age = 0Clean Way:
my_dict = {'name': 'Alice'}
age = my_dict.get('age', 0)5. Use F-Strings for Formatting
(More readable and often faster than other string formatting methods.)
Cluttered Way:
name = "Bob"
age = 30
message = "Hello, " + name + "! You are " + str(age) + " years old."
# Or: message = "Hello, {}! You are {} years old.".format(name, age)
Clean Way:
name = "Bob"
age = 30
message = f"Hello, {name}! You are {age} years old."
6. Use Unpacking to Swap Variables
(A concise, Pythonic way to swap values without a temporary variable.)
Cluttered Way:
a = 5
b = 10
temp = a
a = b
b = temp
Clean Way:
a = 5
b = 10
a, b = b, a
7. Check for Empty Sequences Correctly
(Leverages Python's "truthiness" for more readable code.)
Cluttered Way:
my_list = []
if len(my_list) == 0:
print("List is empty!")
Clean Way:
my_list = []
if not my_list:
print("List is empty!")
8. Use Underscores for Unused Variables
(Signals to other developers that a variable is intentionally ignored.)
Cluttered Way:
# 'i' is created but never used
for i in range(5):
print("Hello")
Clean Way:
for _ in range(5):
print("Hello")
9. Chain Comparison Operators
(Makes numerical range checks more intuitive and readable.)
Cluttered Way:
x = 10
if x > 5 and x < 15:
print("x is between 5 and 15")
Clean Way:
x = 10
if 5 < x < 15:
print("x is between 5 and 15")
10. Return from a Function Early
(Reduces nesting and improves readability by handling edge cases or invalid states first.)
Cluttered Way:
def process_data(data):
if data is not None:
if isinstance(data, list) and len(data) > 0:
# ... deep nested logic here ...
print("Processing data...")
return "Done"
else:
return "Error: Invalid data format."
else:
return "Error: No data provided."
Clean Way:
def process_data(data):
if data is None:
return "Error: No data provided."
if not isinstance(data, list) or not data:
return "Error: Invalid data format."
# ... logic is now at the top level ...
print("Processing data...")
return "Done"
#Python #CleanCode #Programming #BestPractices #CodingTips
βββββββββββββββ
By: @DataScience4 β¨
π‘ Top 10 More Python Clean Code Practices
1. Use Ternary Operators for Simple Conditionals
(Replaces a multi-line
Cluttered Way:
Clean Way:
2. Use
(More efficient and readable than using
Cluttered Way:
Clean Way:
3. Use
(Avoids manual key checking when appending to lists or incrementing counters.)
Cluttered Way:
Clean Way:
4. Use
(Provides readable attribute access instead of relying on numeric indices.)
Cluttered Way:
Clean Way:
5. Use Argument Unpacking (
(Passes all items from a list or dictionary as arguments to a function.)
Cluttered Way:
Clean Way:
6. Use
(More declarative and concise than manual loops with a flag variable.)
Cluttered Way:
Clean Way:
7. Prefer Generator Expressions for Large Datasets
(They don't store the entire sequence in memory, making them highly efficient.)
Cluttered Way (can cause high memory usage):
Clean Way (memory efficient):
8. Use Destructuring for More Powerful Unpacking
(A clean way to assign elements from a sequence to multiple variables.)
Cluttered Way:
Clean Way:
1. Use Ternary Operators for Simple Conditionals
(Replaces a multi-line
if/else block for simple assignments.)Cluttered Way:
is_adult = False
age = 20
if age >= 18:
is_adult = True
Clean Way:
age = 20
is_adult = True if age >= 18 else False
2. Use
str.join() for Concatenating Strings in a List(More efficient and readable than using
+ in a loop.)Cluttered Way:
words = ["hello", "world", "this", "is", "python"]
sentence = ""
for word in words:
sentence += word + " "
Clean Way:
words = ["hello", "world", "this", "is", "python"]
sentence = " ".join(words)
3. Use
collections.defaultdict for Grouping or Counting(Avoids manual key checking when appending to lists or incrementing counters.)
Cluttered Way:
data = [('fruit', 'apple'), ('veg', 'carrot'), ('fruit', 'banana')]
grouped = {}
for category, item in data:
if category not in grouped:
grouped[category] = []
grouped[category].append(item)Clean Way:
from collections import defaultdict
data = [('fruit', 'apple'), ('veg', 'carrot'), ('fruit', 'banana')]
grouped = defaultdict(list)
for category, item in data:
grouped[category].append(item)
4. Use
collections.namedtuple for Simple Data Objects(Provides readable attribute access instead of relying on numeric indices.)
Cluttered Way:
point = (10, 20)
# Unclear what point[0] or point[1] represents
if point[0] > 5:
print("X is greater than 5")
Clean Way:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
point = Point(10, 20)
if point.x > 5:
print("X is greater than 5")
5. Use Argument Unpacking (
* and **)(Passes all items from a list or dictionary as arguments to a function.)
Cluttered Way:
def print_coords(x, y, z):
print(f"X: {x}, Y: {y}, Z: {z}")
coords = [1, 2, 3]
print_coords(coords[0], coords[1], coords[2])
Clean Way:
def print_coords(x, y, z):
print(f"X: {x}, Y: {y}, Z: {z}")
coords_list = [1, 2, 3]
print_coords(*coords_list)
coords_dict = {'x': 4, 'y': 5, 'z': 6}
print_coords(**coords_dict)
6. Use
any() and all() for Boolean Checks on Iterables(More declarative and concise than manual loops with a flag variable.)
Cluttered Way:
numbers = [-1, -2, 5, -4]
has_positive = False
for num in numbers:
if num > 0:
has_positive = True
break
Clean Way:
numbers = [-1, -2, 5, -4]
has_positive = any(num > 0 for num in numbers)
7. Prefer Generator Expressions for Large Datasets
(They don't store the entire sequence in memory, making them highly efficient.)
Cluttered Way (can cause high memory usage):
total = sum([i * i for i in range(1000000)])
Clean Way (memory efficient):
total = sum(i * i for i in range(1000000))
8. Use Destructuring for More Powerful Unpacking
(A clean way to assign elements from a sequence to multiple variables.)
Cluttered Way:
numbers = [1, 2, 3, 4, 5]
first = numbers[0]
last = numbers[-1]
Clean Way:
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
# first = 1, middle = [2, 3, 4], last = 5
9. Use
(It's safer and more robust than
Cluttered Way (brittle, fails on subclasses):
Clean Way (correctly handles subclasses):
10. Use the
(Clearly separates the code that runs on success from the
Cluttered Way:
Clean Way:
#Python #CleanCode #Programming #BestPractices #CodeReadability
βββββββββββββββ
By: @DataScience4 β¨
isinstance() for Type Checking(It's safer and more robust than
type() because it correctly handles inheritance.)Cluttered Way (brittle, fails on subclasses):
class MyList(list): pass
my_list_instance = MyList()
if type(my_list_instance) == list:
print("It's a list!") # This will not print
Clean Way (correctly handles subclasses):
class MyList(list): pass
my_list_instance = MyList()
if isinstance(my_list_instance, list):
print("It's an instance of list or its subclass!") # This prints
10. Use the
else Block in try/except(Clearly separates the code that runs on success from the
try block being monitored.)Cluttered Way:
try:
data = my_ risky_operation()
# It's not clear if this next part can also raise an error
process_data(data)
except ValueError:
handle_error()
Clean Way:
try:
data = my_risky_operation()
except ValueError:
handle_error()
else:
# This code only runs if the 'try' block succeeds with NO exception
process_data(data)
#Python #CleanCode #Programming #BestPractices #CodeReadability
βββββββββββββββ
By: @DataScience4 β¨
β€10π3
β¨ few-shot learning | AI Coding Glossary β¨
π A setting where a model adapts to a new task using only a small number of labeled examples.
π·οΈ #Python
π A setting where a model adapts to a new task using only a small number of labeled examples.
π·οΈ #Python
Learning Common Algorithms with Python
β’ This lesson covers fundamental algorithms implemented in Python. Understanding these concepts is crucial for building efficient software. We will explore searching, sorting, and recursion.
β’ Linear Search: This is the simplest search algorithm. It sequentially checks each element of the list until a match is found or the whole list has been searched. Its time complexity is O(n).
β’ Binary Search: A much more efficient search algorithm, but it requires the list to be sorted first. It works by repeatedly dividing the search interval in half. Its time complexity is O(log n).
β’ Bubble Sort: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The process is repeated until the list is sorted. Its time complexity is O(n^2).
β’ Recursion (Factorial): Recursion is a method where a function calls itself to solve a problem. A classic example is calculating the factorial of a number (
#Python #Algorithms #DataStructures #Coding #Programming #LearnToCode
βββββββββββββββ
By: @DataScience4 β¨
β’ This lesson covers fundamental algorithms implemented in Python. Understanding these concepts is crucial for building efficient software. We will explore searching, sorting, and recursion.
β’ Linear Search: This is the simplest search algorithm. It sequentially checks each element of the list until a match is found or the whole list has been searched. Its time complexity is O(n).
def linear_search(data, target):
for i in range(len(data)):
if data[i] == target:
return i # Return the index of the found element
return -1 # Return -1 if the element is not found
# Example
my_list = [4, 2, 7, 1, 9, 5]
print(f"Linear Search: Element 7 found at index {linear_search(my_list, 7)}")
β’ Binary Search: A much more efficient search algorithm, but it requires the list to be sorted first. It works by repeatedly dividing the search interval in half. Its time complexity is O(log n).
def binary_search(sorted_data, target):
low = 0
high = len(sorted_data) - 1
while low <= high:
mid = (low + high) // 2
if sorted_data[mid] < target:
low = mid + 1
elif sorted_data[mid] > target:
high = mid - 1
else:
return mid # Element found
return -1 # Element not found
# Example
my_sorted_list = [1, 2, 4, 5, 7, 9]
print(f"Binary Search: Element 7 found at index {binary_search(my_sorted_list, 7)}")
β’ Bubble Sort: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The process is repeated until the list is sorted. Its time complexity is O(n^2).
def bubble_sort(data):
n = len(data)
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
if data[j] > data[j+1]:
# Swap the elements
data[j], data[j+1] = data[j+1], data[j]
return data
# Example
my_list_to_sort = [4, 2, 7, 1, 9, 5]
print(f"Bubble Sort: Sorted list is {bubble_sort(my_list_to_sort)}")
β’ Recursion (Factorial): Recursion is a method where a function calls itself to solve a problem. A classic example is calculating the factorial of a number (
n!). It must have a base case to stop the recursion.def factorial(n):
# Base case: if n is 1 or 0, factorial is 1
if n == 0 or n == 1:
return 1
# Recursive step: n * factorial of (n-1)
else:
return n * factorial(n - 1)
# Example
num = 5
print(f"Recursion: Factorial of {num} is {factorial(num)}")
#Python #Algorithms #DataStructures #Coding #Programming #LearnToCode
βββββββββββββββ
By: @DataScience4 β¨
β€1
β¨ Quiz: Python MarkItDown: Convert Documents Into LLM-Ready Markdown β¨
π Practice MarkItDown basics. Convert PDFs, Word documents, Excel documents, and HTML documents to Markdown. Try the quiz.
π·οΈ #intermediate #ai #tools
π Practice MarkItDown basics. Convert PDFs, Word documents, Excel documents, and HTML documents to Markdown. Try the quiz.
π·οΈ #intermediate #ai #tools
Forwarded from Machine Learning with Python
Core Python Cheatsheet.pdf
173.3 KB
Python is a high-level, interpreted programming language known for its simplicity, readability, and
versatility. It was first released in 1991 by Guido van Rossum and has since become one of the most
popular programming languages in the world.
Pythonβs syntax emphasizes readability, with code written in a clear and concise manner using whitespace and indentation to define blocks of code. It is an interpreted language, meaning that
code is executed line-by-line rather than compiled into machine code. This makes it easy to write and test code quickly, without needing to worry about the details of low-level hardware.
Python is a general-purpose language, meaning that it can be used for a wide variety of applications, from web development to scientific computing to artificial intelligence and machine learning. Its simplicity and ease of use make it a popular choice for beginners, while its power and flexibility make it a favorite of experienced developers.
Pythonβs standard library contains a wide range of modules and packages, providing support for
everything from basic data types and control structures to advanced data manipulation and visualization. Additionally, there are countless third-party packages available through Pythonβs package manager, pip, allowing developers to easily extend Pythonβs capabilities to suit their needs.
Overall, Pythonβs combination of simplicity, power, and flexibility makes it an ideal language for a wide range of applications and skill levels.
https://t.me/CodeProgrammer
Please open Telegram to view this post
VIEW IN TELEGRAM
β€2
β¨ Python 3.14 Released and Other Python News for November 2025 β¨
π Python 3.14 is officially out, Python 3.15 begins, and Python 3.9 reaches end of life. Plus, Django 6.0 first beta released, new PEPs, and more Python news.
π·οΈ #community #news
π Python 3.14 is officially out, Python 3.15 begins, and Python 3.9 reaches end of life. Plus, Django 6.0 first beta released, new PEPs, and more Python news.
π·οΈ #community #news
π1
β¨ reasoning model | AI Coding Glossary β¨
π A generative model tuned to solve multi-step problems.
π·οΈ #Python
π A generative model tuned to solve multi-step problems.
π·οΈ #Python
β¨ chain of thought (CoT) | AI Coding Glossary β¨
π A prompting technique that asks models to show intermediate steps, often improving multi-step reasoning but not guaranteeing accurate explanations.
π·οΈ #Python
π A prompting technique that asks models to show intermediate steps, often improving multi-step reasoning but not guaranteeing accurate explanations.
π·οΈ #Python
π Mastering Python Clean Code: 150 Key Principles
π’ Elevate your Python skills! Dive into 150 Clean Code principles to write truly readable and maintainable code for any project.
β‘ Tap to unlock the complete answer and gain instant insight.
βββββββββββββββ
By: @DataScience4 β¨
π’ Elevate your Python skills! Dive into 150 Clean Code principles to write truly readable and maintainable code for any project.
β‘ Tap to unlock the complete answer and gain instant insight.
βββββββββββββββ
By: @DataScience4 β¨
Telegraph
Mastering Python Clean Code: 150 Key Principles
A Comprehensive Guide to 150 Python Clean Code Principles What is Clean Code? Clean Code is a software development philosophy that emphasizes writing code that is easy to read, understand, and maintain. It's not a framework or a library, but a set of principlesβ¦
β€2
β Interview Question
What is the potential pitfall of using a mutable object (like a list or dictionary) as a default argument in a Python function?
Answer: A common pitfall is that the default argument is evaluated only once, when the function is defined, not each time it is called. If that default object is mutable, any modifications made to it in one call will persist and be visible in subsequent calls.
This can lead to unexpected and buggy behavior.
Incorrect Example (The Pitfall):
The Correct, Idiomatic Solution:
The standard practice is to use
tags: #Python #Interview #CodingInterview #PythonTips #Developer #SoftwareEngineering #TechInterview
βββββββββββββββ
By: @DataScience4 β¨
What is the potential pitfall of using a mutable object (like a list or dictionary) as a default argument in a Python function?
Answer: A common pitfall is that the default argument is evaluated only once, when the function is defined, not each time it is called. If that default object is mutable, any modifications made to it in one call will persist and be visible in subsequent calls.
This can lead to unexpected and buggy behavior.
Incorrect Example (The Pitfall):
def add_to_list(item, my_list=[]):
my_list.append(item)
return my_list
# First call seems to work fine
print(add_to_list(1)) # Output: [1]
# Second call has unexpected behavior
print(add_to_list(2)) # Output: [1, 2] -- The list from the first call was reused!
# Third call continues the trend
print(add_to_list(3)) # Output: [1, 2, 3]
The Correct, Idiomatic Solution:
The standard practice is to use
None as the default and create a new mutable object inside the function if one isn't provided.def add_to_list_safe(item, my_list=None):
if my_list is None:
my_list = [] # Create a new list for each call
my_list.append(item)
return my_list
# Each call now works independently
print(add_to_list_safe(1)) # Output: [1]
print(add_to_list_safe(2)) # Output: [2]
print(add_to_list_safe(3)) # Output: [3]
tags: #Python #Interview #CodingInterview #PythonTips #Developer #SoftwareEngineering #TechInterview
βββββββββββββββ
By: @DataScience4 β¨
β€2
Forwarded from Machine Learning with Python
Media is too big
VIEW IN TELEGRAM
Channel owners rise up!
"I want to monetize my telegram channel". It is definitely possible!
Check our website, register your channel today!
Our community homeπ
https://t.me/waybien
Sponsored By WaybienAds
"I want to monetize my telegram channel". It is definitely possible!
Check our website, register your channel today!
Our community homeπ
https://t.me/waybien
Sponsored By WaybienAds
Forwarded from Machine Learning with Python
Please open Telegram to view this post
VIEW IN TELEGRAM
β€1
Python tip:
Use f-strings for easy and readable string formatting.
Python tip:
Utilize list comprehensions for concise and efficient list creation.
Python tip:
Use
Python tip:
Use
Python tip:
Always use the
Python tip:
Use
Python tip:
Use
Python tip:
Employ
Python tip:
Use
Python tip:
Apply type hints to your code for improved readability, maintainability, and to enable static analysis tools.
#PythonTips #PythonProgramming #PythonForBeginners #PythonTricks #CodeQuality #Pythonic #BestPractices #LearnPython
βββββββββββββββ
By: @DataScience4 β¨
Use f-strings for easy and readable string formatting.
name = "Alice"
age = 30
message = f"Hello, my name is {name} and I am {age} years old."
print(message)
Python tip:
Utilize list comprehensions for concise and efficient list creation.
numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers if x % 2 == 0]
print(squares)
Python tip:
Use
enumerate() to iterate over a sequence while also getting the index of each item.fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Python tip:
Use
zip() to iterate over multiple iterables in parallel.names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
Python tip:
Always use the
with statement when working with files to ensure they are properly closed, even if errors occur.with open("example.txt", "w") as f:
f.write("Hello, world!\n")
f.write("This is a test.")
# File is automatically closed herePython tip:
Use
*args to allow a function to accept a variable number of positional arguments.def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3))
print(sum_all(10, 20, 30, 40))
Python tip:
Use
**kwargs to allow a function to accept a variable number of keyword arguments (as a dictionary).def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Bob", age=40, city="New York")
Python tip:
Employ
defaultdict from the collections module to simplify handling missing keys in dictionaries by providing a default factory.from collections import defaultdict
data = [("fruit", "apple"), ("vegetable", "carrot"), ("fruit", "banana")]
categorized = defaultdict(list)
for category, item in data:
categorized[category].append(item)
print(categorized)
Python tip:
Use
if __name__ == "__main__": to define code that only runs when the script is executed directly, not when imported as a module.def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print("Running directly as a script.")
print(greet("World"))
else:
print("This module was imported.")
Python tip:
Apply type hints to your code for improved readability, maintainability, and to enable static analysis tools.
def add(a: int, b: int) -> int:
return a + b
result: int = add(5, 3)
print(result)
#PythonTips #PythonProgramming #PythonForBeginners #PythonTricks #CodeQuality #Pythonic #BestPractices #LearnPython
βββββββββββββββ
By: @DataScience4 β¨
β€4
β¨ Editorial Guidelines β¨
π See how Real Python's editorial guidelines shape comprehensive, up-to-date resources, with Python experts, educators, and editors refining all learning content.
π·οΈ #Python
π See how Real Python's editorial guidelines shape comprehensive, up-to-date resources, with Python experts, educators, and editors refining all learning content.
π·οΈ #Python
β¨ Topic: Python Basics β¨
π Begin your Python journey with these beginner-friendly tutorials. Learn fundamental Python concepts to kickstart your career. This foundation will equip you with the necessary skills to further advance your budding Python programming skills.
π·οΈ #357_resources
π Begin your Python journey with these beginner-friendly tutorials. Learn fundamental Python concepts to kickstart your career. This foundation will equip you with the necessary skills to further advance your budding Python programming skills.
π·οΈ #357_resources
β¨ Send Feedback β¨
π We welcome ideas, suggestions, feedback, and the occasional rant. Did you find a topic confusing? Or did you find an error in the text or code? Send us your feedback via this page.
π·οΈ #Python
π We welcome ideas, suggestions, feedback, and the occasional rant. Did you find a topic confusing? Or did you find an error in the text or code? Send us your feedback via this page.
π·οΈ #Python