An analysis of common mistakes made by Python beginners

1 Introduction

In Python learning, you often encounter various code errors, especially for beginners, who obviously feel that the logic is correct, but when the code runs, it is often not the result you want.

This article expands on a common mistake recently seen on a certain platform, to help you better understand the basic syntax of Python, let’s start without further ado!

2. Problem description

First, let's check the following code to see if there is a problem? The purpose of this code is to remove the even numbers in the list.
insert image description here
Think for two minutes, what do you think the result of running the above code will be?
[1, 7, 11]It is what we want to output, and the above code seems to have no problem. But the result of running the above code is [1, 7, 8, 11], where does the number here 8come from?

3. Problem analysis

The above code output includes numbers 8because the code removes elements from the list as it iterates over the list, causing the list to mutate. We modify the above code to foroutput the temporary variables in each loop, the code is as follows:

def remove_even(nums):
	for i,num in enumerate(nums):
		print("i={} num={}".format(i,num))
		if num%2==0:
			del nums[i]

nums=[1,2,7,4,8,11]
remove_even(nums)
print(nums)

The result of the operation is as follows:

i=0 num=1
i=1 num=2
i=2 num=4
i=3 num=11
[1, 7, 8, 11]

The above operation process is as follows:

  • At that timei=0 , at this time num=1, if the even number judgment is not satisfied, this cycle ends.
  • i=1At that time num=2, the even number judgment is satisfied, and if it is deleted at nums[1]this time, the list will change to [1,7,4,8,11];
  • i=2At that time num=4, the even number judgment is satisfied, and if it is deleted at nums[2]this time, the list will change to [1,7,8,11];
  • At that timei=3 , at this time num=11, the even-number judgment is not satisfied, and the loop ends. The final list becomes [1,7,8,11].

4. Solution 1

To avoid this problem, it is better to create a new list to store only elements that do not satisfy the conditional statement, rather than modifying the original list while iterating. For example:
insert image description here
the above code will output after running [1,7,11], which is the result we want. Of course there are other more elegant implementations.

5. Solution 2

yieldis a keyword in Python used to define a generator function. A generator is a special type of function that can be used to generate a sequence of values ​​dynamically, instead of returning all the values ​​at once like a regular function. When a yield statement is executed inside a generator function, it temporarily suspends the execution of the function and yieldreturns the value of the expression via the keyword. The function is not terminated, but is in a suspended state, and can continue to resume from the place where it was suspended.

yieldThe sample code to implement the above functions with keywords is as follows: In
insert image description here
this code, remove_evenit is a generator function that numbersgenerates an odd number from the input list at a time. Then use list()the constructor to remove_evenconvert the returned generator object into a list. Using generators also allows for more flexible and memory-efficient processing of large or infinite data sequences.

6. Summary

This article focuses on the low-level mistakes that beginners tend to make when deleting list elements in Python, and proposes two targeted solutions, which can process larger-scale data lists more flexibly and efficiently.

Hmm, have you lost your studies?

Guess you like

Origin blog.csdn.net/sgzqc/article/details/130453795