Can you give me some more examples of how we can use these features to make our code even better? Maybe something related to working with lists or dictionaries?
Let’s say you have a function that takes in a list as an argument, performs some operations on it, and returns the modified list. Here’s what your signature might look like:
# This function takes in a list of integers as an argument and returns a modified list of integers.
def modify_list(input_list: List[int]) -> List[int]:
# Create an empty list to store the modified values
modified_list = []
# Loop through each element in the input list
for num in input_list:
# Check if the element is even
if num % 2 == 0:
# Divide the element by 2 and append it to the modified list
modified_list.append(num // 2)
# If the element is odd
else:
# Multiply the element by 3 and add 1, then append it to the modified list
modified_list.append(num * 3 + 1)
# Return the modified list
return modified_list
In this example, we’re using type hinting to specify that `input_list` should be a list of integers. This can help catch errors at compile time instead of runtime, and it also makes your code more readable for other developers who might not be familiar with the specifics of what you’re doing.
As for docstrings, let’s say you have another function that takes in a dictionary as an argument:
# This function takes in a dictionary as an argument and modifies it by adding a new key-value pair.
def modify_dict(input_dict: Dict[str, int]) -> Dict[str, int]:
# Create a new key-value pair with key "new_key" and value 5
new_key: str = "new_key"
new_value: int = 5
# Add the new key-value pair to the input dictionary
input_dict[new_key] = new_value
# Return the modified dictionary
return input_dict
In this case, we’re using type hinting to specify that `input_dict` should be a dictionary with string keys and integer values. Again, this can help catch errors at compile time instead of runtime, and it also makes your code more readable for other developers who might not be familiar with the specifics of what you’re doing.
Here are some examples of how we could use these features to work with lists or dictionaries:
1. Sorting a list in place using `sort()` instead of creating a new sorted list and assigning it back to the original variable name (which can be less efficient):
# This function takes in a list of integers and sorts it in place
def sort_list(input_list: List[int]) -> None:
"""Sorts input_list in place.""" # This is a docstring that explains the purpose of the function
input_list.sort() # This is the correct way to sort a list in place, without creating a new sorted list and assigning it back to the original variable name. This is more efficient.
# Example usage:
my_list = [5, 2, 8, 1, 3]
sort_list(my_list)
print(my_list) # Output: [1, 2, 3, 5, 8]
2. Removing duplicates from a list using `set()` and converting it back to a list (which can be less efficient than using the built-in `list(set())` method):
# This function takes in a list of integers and removes any duplicates from it
def remove_duplicates(input_list: List[int]) -> List[int]:
"""Removes duplicates from input_list.""" # Function description
unique_list = list(set(input_list)) # Using set() to remove duplicates and converting it back to a list
return unique_list # Returning the unique list without duplicates
3. Filtering a list using a lambda function and the built-in `filter()` method (which can be less efficient than using a list comprehension):
# This function takes in a list of integers and returns a new list with only positive integers.
def filter_list(input_list: List[int]) -> List[int]: # Declaring a function named filter_list that takes in a list of integers as input and returns a list of integers as output.
"""Filters input_list based on some condition.""" # Docstring explaining the purpose of the function.
return [x for x in input_list if x > 0] # Using list comprehension to filter the input_list and only keep elements that are greater than 0. This is more efficient than using the built-in filter() method.
# Example usage:
numbers = [-1, 2, -3, 4, -5, 6]
filtered_numbers = filter_list(numbers)
print(filtered_numbers) # Output: [2, 4, 6]
4. Converting a dictionary to a sorted list of tuples using `sorted()` and the built-in `items()` method (which can be less efficient than using a list comprehension):
# This function takes in a dictionary with string keys and integer values
def sort_dict(input_dict: Dict[str, int]) -> List[(str, int)]:
# Sorts the dictionary by key using the built-in sorted() function
# and returns a list of tuples
return sorted(input_dict.items())
# Example dictionary
example_dict = {"b": 2, "a": 1, "c": 3}
# Calling the function and storing the sorted list of tuples in a variable
sorted_list = sort_dict(example_dict)
# Printing the sorted list of tuples
print(sorted_list)
# Output: [('a', 1), ('b', 2), ('c', 3)]
5. Converting a list to a dictionary using `dict()` and the built-in `zip()` method (which can be less efficient than using a dict comprehension):
# Converting a list to a dictionary using `dict()` and the built-in `zip()` method
# Define a function named `convert_list_to_dict` that takes in a list of tuples as input and returns a dictionary
def convert_list_to_dict(input_list: List[Tuple[str, int]]) -> Dict[str, int]:
"""Converts input_list to a dictionary.""" # Function documentation explaining the purpose of the function
# Use the built-in `zip()` method to combine the elements of the input list into tuples
# The `*` operator unpacks the elements of the input list, allowing them to be passed as separate arguments to `zip()`
# This creates a list of tuples where the first element of each tuple is the key and the second element is the value
# Example: [('a', 1), ('b', 2), ('c', 3)]
# Note: This method can be less efficient than using a dict comprehension
zipped_list = zip(*input_list)
# Use the `dict()` function to convert the zipped list into a dictionary
# This function takes in an iterable of key-value pairs and returns a dictionary with those key-value pairs
# Example: {'a': 1, 'b': 2, 'c': 3}
return dict(zipped_list)
These are just a few examples of how you can use type hinting and docstrings to make your code more efficient and readable. By following these best practices, you’ll be able to write better code that other developers will appreciate!