0 Basics python-12.5 Modifying lists and modifying lists with for and range

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.