Comparison of two methods for clearing the dictionary in python

Source: Internet
Author: User
Two methods for clearing the dictionary in python: clear indicates clearing the dictionary content in python. it is different from deleting the dictionary. comparison between the two methods for clearing the dictionary in python

Clear refers to clearing the dictionary content in python, which is different from deleting the dictionary.

For example:

D = {'name': 1, 'age': 2}

There are two methods to clear the dictionary.

Method 1:

D. clear ()

Print the value of d {}

Method 2:

D = {}

Print the value of d {}

Differences between the two:

>>> D = {'name': 1, 'age': 2}

>>> X = d

>>> X

{'Age': 2, 'name': 1}

>>> X = {}

>>> X

{}

>>> D

{'Age': 2, 'name': 1}

>>>

We can see that when x = {} is used, the value of x itself is cleared, that is, the reference of x to d is changed, and the value of d is not changed.

>>> D = {'namge': 1, 'age': 2}

>>> X = d

>>> X

{'Namge': 1, 'age': 2}

>>> D

{'Namge': 1, 'age': 2}

>>> X. clear ()

>>> X

{}

>>> D

{}

>>>

When X = clear (), the value in the reference is cleared. when x = clear () is used, the value of d also changes, the value of D does not change when x = {} is used.

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.