This article is approximately 2,700 words and it is recommended to read 7 minutes
This article introduces 16 Python programming tips.
Mastering these skills can not only improve programming efficiency, but also make your code more beautiful and efficient, which will make people’s eyes shine! If you want to take a step further in programming, you might as well give it a try.
Tips to make life easier as a Python developer
Introduction
As a programming language, Python has a large number of libraries and frameworks and is widely used. However, there are some Python programming techniques and libraries that few people know about, and if developers can master these techniques, they will make their lives easier and their code more efficient.
In this article, we’ll explore some little-known but useful Python tricks. Learning and implementing these techniques can help you save time and energy in coding, making your code more elegant and efficient. Now let’s dive into these hidden gems of the Python language!
1. Ternary operator
The ternary operator is a shorthand form of if-else statement. The syntax is: value_if_true if condition else value_if_false. It can replace multiple lines of if-else statements, making the code more concise.
a = 5 b = 10 max = a if a > b else b ##value_if_true if condition else value_if_false print(max) #10
The above query checks if “a” is greater than “b” and returns “a” if true and “b” if false.
2. Enumeration function
The enumerate() enumeration function adds a counter to an iterable object and returns it as an enumeration object. This function is useful when you want to iterate over a list and keep track of the index at the same time.
fruits = ['apple', 'banana', 'mango'] for index, fruit in enumerate(fruits): print(index, fruit) #0 apple #1 banana #2 mango
3. zip function
The zip() function aggregates elements from multiple iterables and returns an iterator consisting of tuples. This function is useful when you want to iterate through two or more lists at the same time.
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] for x, y in zip(list1, list2): print(x, y) #1 a #2b #3c
4. List comprehension
List comprehensions are a concise way to create a list from an existing list or any iterable object. Its syntax requires only one line of code and can replace the for loop, making the code more efficient and easier to read.
squared_numbers = [x**2 for x in range(1, 6)] print(squared_numbers) #[1, 4, 9, 16, 25]
5. Lambda function
Lambda functions are anonymous functions defined using the lambda keyword. This function is useful when you want to write small, one-off functions and don’t want to use the def keyword to define named functions.
add = lambda x, y: x + y result = add(3, 4) print(result) #7
6. Any and all functions
The any() and all() functions return True or False based on the truthiness of the elements in the iterable. The any() function returns True if any element in the iterable is true, while the all() function returns True if all elements in the iterable are true.
numbers = [1, 2, 3, 0, 4] result = any(numbers) #True result = all(numbers) # False. 0 is making it false
7. Itertools
The itertools module provides a set of functions for working with iterators, but they are not widely known. Some of the functions in this module include chain, product, and permutations.
import itertools numbers = [1, 2, 3] result = list(itertools.permutations(numbers)) #output all the permutations #[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
8. Generator
Generators are an iterator type that generate values on the fly rather than storing them in memory. They are defined using the yield keyword and can be used to create custom iterators.
### Generators created using yield keyword def fibonacci_series(n): a, b = 0, 1 for i in range(n): yield a a, b = b, a + b # Driver code to check above generator function for number in fibonacci_series(10): print(number) #0 #1 #1 #2 #3 #5 #8 #13 #twenty one #34
9. Decorator
Decorators are a way to modify the behavior of a function or class. They are defined using the @ symbol and can be used to add functionality to functions such as logging, timing, or authentication.
def log_function(func): def wrapper(*args, **kwargs): print(f'Running {<!-- -->func.__name__}') result = func(*args, **kwargs) print(f'{<!-- -->func.__name__} returned {<!-- -->result}') return result return wrapper @log_function def add(x, y): return x + y print(add(5,7)) #Running add #add returned 12 #12
10. Multiple function parameters
In Python, you can use the * and ** operators to handle multiple function arguments. The * operator is used to pass the parameter list as separate positional parameters, while the ** operator is used to pass a dictionary of keyword parameters.
def print_arguments(*args, **kwargs): print(args) print(kwargs) print_arguments(1, 2, 3, name='John', age=30) #(1, 2, 3) #{'name': 'John', 'age': 30}
11. Dynamic import
You can dynamically import a module using the importlib module. This is useful when you want to import a module based on user input or configuration.
import importlib module_name = 'math' module = importlib.import_module(module_name) result = module.sqrt(9)
12. Dictionary derivation
Dictionary comprehensions are a concise way to create a dictionary from an existing dictionary or any iterable object. It is a one-line statement that can replace a for loop, making your code more efficient and readable.
squared_numbers = {<!-- -->x: x**2 for x in range(1, 6)} print(squared_numbers) #{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
13. Callable objects
In Python, anything that can be called is called a callable object. This includes functions, methods, classes, and even objects that have a __call__ method defined.
class Adder: def __call__(self, x, y): return x + y adder = Adder() result = adder(3, 4) print(result) #7
14. Use underscores to separate large numbers/characters
Large numbers are difficult to decipher at first glance, so Python provides the ability to place underscores between numbers to make numbers more readable.
num_test = 100_345_405 # this is the number print(num_test) ## 100345405
15. Quickly merge two dictionaries
We can quickly merge two Python dictionaries using the following code.
dictionary_one = {<!-- -->"a": 1, "b": 2} dictionary_two = {<!-- -->"c": 3, "d": 4} merged = {<!-- -->**dictionary_one, **dictionary_two} print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
16. Mutable lists, sets and dictionaries
Mutable means that we can change or update an object (list, set or dictionary) without changing the pointer of the object in memory. Let’s look at an example.
cities = ["Munich", "Zurich", "London"] print(id(cities)) # 2797174365184 cities.append("Berlin") print(id(cities)) # 2797174365184
####Sets my_set = {<!-- -->1, 2, 3} print(id(my_set)) # 2797172976992 my_set.add(4) print(id(my_set)) # 2797172976992
###Dictionary thisdict = {<!-- --> "brand": "Ford", "model": "Mustang", "year": 1964 } print(id(thisdict)) #2797174128256 thisdict["engine"] = "2500cc" print(id(thisdict)) #2797174128256
In the example below, we update the list of cities by appending new cities. We can see that the ID (object pointer) remains unchanged. The same goes for collections and dictionaries.
I hope you gained something from reading this article.
Finally:
Python learning materials
If you want to learn Python to help you automate your office, or are preparing to learn Python or are currently learning it, you should be able to use the following and get it if you need it.
① A roadmap for learning Python in all directions, knowing what to learn in each direction
② More than 100 Python course videos, covering essential basics, crawlers and data analysis
③ More than 100 Python practical cases, learning is no longer just theory
④ Huawei’s exclusive Python comic tutorial, you can also learn it on your mobile phone
⑤Real Python interview questions from Internet companies over the years, very convenient for review
There are ways to get it at the end of the article
1. Learning routes in all directions of Python
The Python all-direction route is to organize the commonly used technical points of Python to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.
2. Python course video
When we watch videos and learn, we can’t just move our eyes and brain but not our hands. The more scientific learning method is to use them after understanding. At this time, hands-on projects are very suitable.
3. Python practical cases
Optical theory is useless. You must learn to follow along and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.
4. Python comic tutorial
Use easy-to-understand comics to teach you to learn Python, making it easier for you to remember and not boring.
5. Internet company interview questions
We must learn Python to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and Alibaba bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.
This complete version of the complete set of Python learning materials has been uploaded to CSDN. If you need it, friends can scan the official QR code of csdn below or click on the WeChat card under the homepage and article to get the method, [guaranteed 100% free] strong>