💡 Python Tips Part 1
A collection of essential Python tricks to make your code more efficient, readable, and "Pythonic." This part covers list comprehensions, f-strings, tuple unpacking, and using
• List Comprehensions: A concise and often faster way to create lists. The syntax is
• F-Strings: The modern, readable way to format strings. Simply prefix the string with
• Extended Unpacking: Use the asterisk
• Using
#Python #Programming #CodeTips #PythonTricks
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
A collection of essential Python tricks to make your code more efficient, readable, and "Pythonic." This part covers list comprehensions, f-strings, tuple unpacking, and using
enumerate.# Create a list of squares from 0 to 9
squares = [x**2 for x in range(10)]
print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
• List Comprehensions: A concise and often faster way to create lists. The syntax is
[expression for item in iterable].name = "Alex"
score = 95.5
# Using an f-string for easy formatting
message = f"Congratulations {name}, you scored {score:.1f}!"
print(message)
# Output: Congratulations Alex, you scored 95.5!
• F-Strings: The modern, readable way to format strings. Simply prefix the string with
f and place variables or expressions directly inside curly braces {}.numbers = (1, 2, 3, 4, 5)
# Unpack the first, last, and middle elements
first, *middle, last = numbers
print(f"First: {first}") # 1
print(f"Middle: {middle}") # [2, 3, 4]
print(f"Last: {last}") # 5
• Extended Unpacking: Use the asterisk
* operator to capture multiple items from an iterable into a list during assignment. It's perfect for separating the "head" and "tail" from the rest.items = ['keyboard', 'mouse', 'monitor']
for index, item in enumerate(items):
print(f"Item #{index}: {item}")
# Output:
# Item #0: keyboard
# Item #1: mouse
# Item #2: monitor
• Using
enumerate: The Pythonic way to get both the index and the value of an item when looping. It's much cleaner than using range(len(items)).#Python #Programming #CodeTips #PythonTricks
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤2
💡 Python Tips Part 2
More essential Python tricks to improve your code. This part covers dictionary comprehensions, the
• Dictionary Comprehensions: A concise way to create dictionaries, similar to list comprehensions. The syntax is
• Using
• Ternary Operator: A shorthand for a simple
• Using Underscore
#Python #Programming #CodeTips #PythonTricks
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
More essential Python tricks to improve your code. This part covers dictionary comprehensions, the
zip function, ternary operators, and using underscores for unused variables.# Create a dictionary of numbers and their squares
squared_dict = {x: x**2 for x in range(1, 6)}
print(squared_dict)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
• Dictionary Comprehensions: A concise way to create dictionaries, similar to list comprehensions. The syntax is
{key_expr: value_expr for item in iterable}.students = ["Alice", "Bob", "Charlie"]
scores = [88, 92, 79]
for student, score in zip(students, scores):
print(f"{student}: {score}")
# Output:
# Alice: 88
# Bob: 92
# Charlie: 79
• Using
zip: The zip function combines multiple iterables (like lists or tuples) into a single iterator of tuples. It's perfect for looping over related lists in parallel.age = 20
# Assign a value based on a condition in one line
status = "Adult" if age >= 18 else "Minor"
print(status)
# Output: Adult
• Ternary Operator: A shorthand for a simple
if-else statement, useful for conditional assignments. The syntax is value_if_true if condition else value_if_false.# Looping 3 times without needing the loop variable
for _ in range(3):
print("Hello, Python!")
# Unpacking, but only needing the last value
_, _, last_item = (10, 20, 30)
print(last_item) # 30
• Using Underscore
_: By convention, the underscore _ is used as a variable name when you need a placeholder but don't intend to use its value. This signals to other developers that the variable is intentionally ignored.#Python #Programming #CodeTips #PythonTricks
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤1
💡 Python Tips Part 3
Advancing your Python skills with more powerful techniques. This part covers safe dictionary access with
• Dictionary
•
• The
#Python #Programming #CodeTips #PythonTricks
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
Advancing your Python skills with more powerful techniques. This part covers safe dictionary access with
.get(), flexible function arguments with *args and **kwargs, and context managers using the with statement.user_data = {"name": "Alice", "age": 30}
# Safely get a key that exists
name = user_data.get("name")
# Safely get a key that doesn't exist by providing a default
city = user_data.get("city", "Not Specified")
print(f"Name: {name}, City: {city}")
# Output: Name: Alice, City: Not Specified• Dictionary
.get() Method: Access dictionary keys safely. .get(key, default) returns the value for a key if it exists, otherwise it returns the default value (which is None if not specified) without raising a KeyError.def dynamic_function(*args, **kwargs):
print("Positional args (tuple):", args)
print("Keyword args (dict):", kwargs)
dynamic_function(1, 'go', True, user="admin", status="active")
# Output:
# Positional args (tuple): (1, 'go', True)
# Keyword args (dict): {'user': 'admin', 'status': 'active'}
•
*args and **kwargs: Use these in function definitions to accept a variable number of arguments. *args collects positional arguments into a tuple, and **kwargs collects keyword arguments into a dictionary.# The 'with' statement ensures the file is closed automatically
try:
with open("notes.txt", "w") as f:
f.write("Context managers are great!")
# No need to call f.close()
print("File written and closed.")
except Exception as e:
print(f"An error occurred: {e}")
• The
with Statement: The with statement creates a context manager, which is the standard way to handle resources like files or network connections. It guarantees that cleanup code is executed, even if errors occur inside the block.#Python #Programming #CodeTips #PythonTricks
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
💡 Python Tips Part 4
Level up your Python code with more advanced tips. This part covers chaining comparisons, using sets for uniqueness, and powerful tools from the
• Chaining Comparisons: Python allows you to chain comparison operators for more readable and concise range checks. This is equivalent to
• Sets for Uniqueness: Sets are unordered collections of unique elements. Converting a list to a set and back is the fastest and most Pythonic way to remove duplicates.
•
•
#Python #Programming #CodeTips #DataStructures
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
Level up your Python code with more advanced tips. This part covers chaining comparisons, using sets for uniqueness, and powerful tools from the
collections module like Counter and defaultdict.x = 10
# Check if x is between 5 and 15 in a clean way
if 5 < x < 15:
print("x is in range.")
# Output: x is in range.
• Chaining Comparisons: Python allows you to chain comparison operators for more readable and concise range checks. This is equivalent to
(5 < x) and (x < 15).numbers = [1, 2, 2, 3, 4, 4, 4, 5]
# Use a set to quickly get unique elements
unique_numbers = list(set(numbers))
print(unique_numbers)
# Output: [1, 2, 3, 4, 5]
• Sets for Uniqueness: Sets are unordered collections of unique elements. Converting a list to a set and back is the fastest and most Pythonic way to remove duplicates.
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)
print(word_counts)
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})
print(word_counts.most_common(1))
# Output: [('apple', 3)]
•
collections.Counter: A specialized dictionary subclass for counting hashable objects. It simplifies frequency counting tasks and provides useful methods like .most_common().from collections import defaultdict
data = [('fruit', 'apple'), ('fruit', 'banana'), ('veg', 'carrot')]
grouped_data = defaultdict(list)
for category, item in data:
grouped_data[category].append(item)
print(grouped_data)
# Output: defaultdict(<class 'list'>, {'fruit': ['apple', 'banana'], 'veg': ['carrot']})
•
collections.defaultdict: A dictionary that provides a default value for a non-existent key, avoiding KeyError. It's perfect for grouping items into lists or dictionaries without extra checks.#Python #Programming #CodeTips #DataStructures
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤1