Python is a powerful and versatile programming language that can be used for many applications. Here are some tips and tricks that can help you write better Python code:
-
Unpacking Elements from Iterables:
a, b, c = [1, 2, 3]
This assigns values 1, 2, and 3 to variables a, b, and c.
-
List Comprehensions:
squares = [x**2 for x in range(10)]
This creates a list of squares from 0 to 9.
-
Using enumerate for Index and Value:
for index, value in enumerate(my_list): print(f"Index: {index}, Value: {value}")
Enumerate helps you loop over both the index and value of a list.
-
Dictionary Comprehensions:
squares_dict = {x: x**2 for x in range(5)}
This creates a dictionary with keys and values being the square of the keys.
-
Unpacking Operator (
*
and**
):a, *rest = [1, 2, 3, 4]
This assigns 1 to a and the rest of the list to rest.
-
Lambda Functions:
add = lambda x, y: x + y
Lambda functions are concise anonymous functions.
-
Zip Function:
names = ["Alice", "Bob", "Charlie"] ages = [25, 30, 35] combined = list(zip(names, ages))
Zip combines two lists element-wise.
-
Using
with
for File Handling:with open("file.txt", "r") as file: content = file.read()
The
with
statement ensures proper file handling (closing) even if an exception occurs. -
Default Values in Dictionary:
age = person.get("age", 25)
This sets the default value of age to 25 if it's not present in the dictionary.
-
Ternary Conditional Expression:
result = "even" if x % 2 == 0 else "odd"
A concise way for conditional assignments.
-
any
andall
Functions:any([True, False, False]) # True all([True, True, True]) # True
any
returns True if at least one element is True;all
returns True if all elements are True. -
collections
Module - Counter:from collections import Counter counts = Counter([1, 2, 2, 3, 3, 3, 4])
Counts the occurrences of elements in a list.
-
Multiple Assignments in One Line:
a, b, c = 1, 2, 3
Multiple variables can be assigned in one line.
-
String Formatting (f-strings):
name = "Alice" greeting = f"Hello, {name}!"
f-strings make string formatting concise.
-
Using
map
for Iterables:numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers))
Applies a function to all items in an input list.
-
else
Clause in Loops:for i in range(3): print(i) else: print("Loop completed!")
The
else
block is executed after the loop completes normally. -
Destructuring in Nested Data Structures:
person = {"name": "Alice", "age": 30, "address": {"city": "Wonderland", "zip": "12345"}} city = person.get("address", {}).get("city", "Unknown")
Safely extract nested values.
-
filter
Function:numbers = [1, 2, 3, 4, 5, 6] evens = list(filter(lambda x: x % 2 == 0, numbers))
Filters elements based on a function.
-
Formatted String Literals (f-strings) for Floats:
pi = 3.14159 formatted_pi = f"{pi:.2f}"
Formats floating-point numbers to a specified number of decimal places.
-
sorted
Function with Custom Key:words = ["apple", "banana", "kiwi", "grape"] sorted_words = sorted(words, key=lambda x: len(x))
Sorts a list based on a custom key.
-
Underscore for Large Numbers:
large_number = 1_000_000
Underscores can be used to make large numbers more readable.
-
zip
Unpacking:names = ["Alice", "Bob"] ages = [30, 25] combined = list(zip(names, ages)) unzipped_names, unzipped_ages = zip(*combined)
Unpacks elements from zipped lists.
-
itertools
Module -product
:from itertools import product combinations = list(product([1, 2], repeat=2))
Generates the Cartesian product of input iterables.
-
try
,except
,else
,finally
:try: result = x / y except ZeroDivisionError: print("Cannot divide by zero!") else: print(f"Result: {result}") finally: print("Execution complete!")
Handling exceptions and executing code regardless of exceptions.
-
collections
Module -defaultdict
:from collections import defaultdict my_dict = defaultdict(int) my_dict["key"] += 1
Creates a dictionary with default values.
"