This chapter talks about using for and range to modify the list, and most people will think of the following code when they encounter this scenario:
But why the result is not right?
Let's take a look at its running steps:
1. Remove an object from List A
2. Assign a value to X for the object you just made
3.x self-Add 1
As you can see here, x refers to Object 1, which is the same object as the object referenced by the first object in the list, and it should be replaced, the problem is here, in fact, the object that X points to has changed, but you don't know it.
Let's take a look at the following set of code:
The above code we have added a x+=1 to print the object ID of the x before and after the statement, printed a lot of IDs out, we can see from the change in the ID, X has been changing, this is because the integer in the Python is not changeable
If we want to change the list above, we need to follow the following method:
By iterating through the list, using the index to execute the object inside the list, change its value
This chapter mainly describes the misunderstanding of changing the list, and using the for and range to change the list
This chapter is here, thank you.
------------------------------------------------------------------
Click to jump 0 basic python-Catalogue
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
0 Basics python-12.5 Modifying lists and modifying lists with for and range