Six Common Python Syntax Sugars: Learn One and Get a Salary Increase

Recently, I have been studying Python for a while, and I have gained a deeper understanding of its code structure and syntax. Therefore, I decided to organize the differences of Python compared to other languages. The first and foremost is Python’s syntax sugar, so below I will summarize the commonly used syntax sugars in Python. Learning these can double your efficiency, so learning just one can be a reason to ask your boss for a raise.1. List ComprehensionUse case: To perform a certain operation on each value in a list and create a new list from the results. For example: getting the square of each value in [1,2,3,4]: [1,4,9,16]. The traditional code is as follows:

list = [1,2,3,4]list_res = []for i in list:    i=i*i    list_res.append(i)print(f"Traditional method: {list_res}")

Using Python’s syntax sugar simplifies it to:

list = [1,2,3,4]list = [i*i for i in list]print(f"Syntax sugar method: {list}")

No need to create a new object, no need for a for loop, no need for append; all solved in one line of code.Advanced: If you only want to operate on specific conditions, such as squaring only even numbers, the original code is:

list = [1,2,3,4]list_res = []for i in list:  if i%2==0:     i=i*i    list_res.append(i)print(f"Traditional method: {list_res}")

Syntax sugar method: also extremely concise in one line

list = [1,2,3,4]list = [i*i for i in list if i % 2 == 0]print(f"Syntax sugar method: {list}")

Advanced 2: Not limited to traditional lists [], but also includes dictionaries dict (the most widely used and useful type in Python) and other collection types, for example:

dict = {'apple':'red', 'banana':'yellow', 'cherry':'red'}dict = { key:value  for key,value in dict.items() if value == 'red'}print(f"dic: {dict}") # Output: dic: {'apple': 'red', 'cherry': 'red'}

Key point: Use dict.items() for iterationSummary: This writing style is generally applicable to all collection types, effectively omitting large blocks of code that would otherwise require for+if or filter + map.2. Temporary File Operations with withIf you want to read a file, the common operation is as follows:

try:    file= open('sample.txt', 'w')    file.write("Hello, World!")finally:    file.close()print("File operation completed")

It requires a lot of try and finally to close the file, preventing memory leaks that may occur during abnormal file operations. The with syntax sugar simplifies this code:

with open('sample.txt', 'w') as file:    file.write("Hello, World")print("File operation completed")

No need for finally and closeAdvanced: The actual function of with is that when entering and exiting the object, it automatically executes the object’s __enter__() and __exit__() methods to clear resources and prevent leaks. It can be used in many scenarios, such as automatically locking and unlocking Redis, automatically connecting and disconnecting from a database, and automatically locking and unlocking threads, for example:

# Automatically call the database object and release it after use:with connection.cursor() as cursor:    cursor.execute("SELECT * FROM table") # Automatically lock with lock:    # do something

3. Quickly Retrieve List ValuesFirst, look at a piece of code:

values = [1, 2, 3,4]x = values[0]y = values[1]z = values[2]v = values[2]print(f"Traditional multiple variable assignment: x={x}, y={y}, z={z}, v={v}")

This is a normal writing style. This syntax sugar is to omit the process of assigning values to x, y, z, and v, as follows:

x, y, z, v= valuesprint(f"Sequence unpacking: x={x}, y={y}, z={z},v={v}")

Directly using commas to retrieve values. You might wonder what happens if the number of variables does not match? In this case, there is actually an advanced writing style that uses dynamic parameters in Python:

x, *y, v= values# Result: x=1, y=[2, 3] , v=4 (y is in array form)x, *y, z, v= values# Result: x=1, y=[2],z=3,v=4 (y is also an array)

*y will automatically assign excess parameters in the form of an array (also called a tuple in Python).Expansion:Dynamic parameters, in addition to adding one asterisk: *y, there is also adding two asterisks: **y, where excess parameters will be saved in the form of a dictionary (like this: {‘a’:’1′,’b’:’2′}). Of course, the two asterisks cannot be used in this syntax sugar; they are generally used for method parameters when the number of parameters is uncertain, typically for fallback purposes. For example:

# Method definitiondef methodA (x, y, **other):  print(x,y,**other)# Method callmethodA(x=1,y=2,z=3,v=4)# Print result  1 2 {'z': 3, 'v': 4}

4. Walrus Operator (also known as assignment expression, because its symbol := resembles an inverted walrus)Example of usage:

a = 10 ,b = 20 a = a+bif a > 10:    print(f"a+b is greater than 10")

Here we see if a=a+b and if a > 10 can be merged?

if a:= a+b >10 :  print(f"a+b is greater than 10")

At first glance, it looks similar to a+=b, which is equivalent to a=a+b, but a= a+b >10 cannot be compiled because a = a+b is not a chain return and does not return a for further operations.So a := a+b >10 actually optimizes the code as a chain return, similar to a.setA().setB().setC() in Java, where each method returns the object itself for further calls.Complete functionality description:a := a+b assigns the value of a+b to a and then returns the value of a, thus several common scenarios can be listed:

# Used with methods, only correct password can pass verification, input("Enter password: ") can receive console inputwhile (p := input("Enter password: ")) != "yourpassword":   continue# Elegantly checking if the end line is reached, terminating when nullfile = open("demo.txt", "r")while (line := file.readline()):    print(line.strip())# Returning the processed return value listres = [resultItem for dataItem in dataList if (resultItem := getAge(dataItem)) >3]

5. Dictionary Merging

# Merging dictionaries (Python 3.9+)dict1 = {'a': 1, 'b': 2}dict2 = {'b': 3, 'c': 4}merged_sugar = dict1 | dict2# Result: {'a': 1, 'b': 3, 'c': 4}

Leave a Comment