Comparison of two methods of Python empty dictionary

Source: Internet
Author: User
Comparison of two methods of Python empty dictionary

The clear in this case means emptying the contents of the dictionary in Python, not the same as deleting the dictionary.

For example:

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

There are two ways to empty the dictionary

Method 1:

D.clear ()

Print out the value of D as {}

Method 2:

d={}

The value of print D is {}

The difference between the two:

>>> d={' name ': 1, ' Age ': 2}

>>> x = d

>>> x

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

>>> x = {}

>>> x

{}

>>> D

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

>>>

You can see that when you use x={}, the value of x itself is cleared, and the reference 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 () clears the value in the reference, the value of D is changed when X=clear () is used, while the value of D is not changed when using x={}.

  • 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.