Comparison of two methods for clearing dictionaries in python

高洛峰
Release: 2016-10-20 09:22:56
Original
1773 people have browsed it

Comparison of two methods of clearing the dictionary in python

The clear mentioned here refers to clearing the dictionary contents 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 out d The value is {}

Method 2:

d={}

The value of printed d is {}

The difference between the two:

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

>>> x = d

>>> x

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

>>> x = {}

>>>

>>> d

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

>>>

You can see that when using x={}, what is cleared is the value of x itself, that is, the value of x to d The reference is changed, but 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, and when using The value of D does not change when x={}.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template