Python: dict={} vs dict.clear()

By Xah Lee. Date: . Last updated: .

In Python, there are 2 ways to clear a hash: myHash = {} and myHash.clear(). What is the difference?

The difference is that myHash={} simply creates a new empty hash and assigns to myHash, while myHash.clear() actually clear the hash the myHash is pointing to.

What does that mean? Here's a code that illustrates:

# python 3

# 2 ways to clear hash and their difference

aa = {'a':3, 'b':4}
bb = aa
aa = {}
print(bb)
# {'a': 3, 'b': 4}

aa = {'a':3, 'b':4}
bb = aa
aa.clear()
print(bb)
# {}

This is like this because of the “reference” concept. The opposite alternative, is that everything is a copy, for example in most functional langs. (with respect to programer-visible behavior, not how it is implemented)

From the aspect of the relation of the language source code to the program behavior by the source code, this “reference”-induced behavior is similar to dynamic scope vs lexical scope. The former being un-intuitive and hard to understand the latter more intuitive and clear. The former requires the lang to have a internal model of the language, the latter more correspond to source code WYSIWYG. The former being easy to implement and is in early langs, the latter being more popular today.

As with many languages that have concept of references, or pointers, this is a complexity that hampers programing progress. The concept of using some sort of “reference” as part of the language is due to implementation efficiency. Starting with C and others in 1960s up to 1990s. But as time went on, this concept in computer languages are gradually disappearing, as they should.

Other langs that have this “reference” concept as ESSENTIAL part of the semantic of the language, includes: C, C++, Java, Perl, Common Lisp. (of course, each using different terminologies, and each lang faction will gouge the other faction's eyes out about what is the true meaning of terms like “reference”, “object”, {list, sequence, vector, array, hash}, and absolutely pretend other meanings do not exist. (partly due to, their ignorance of langs other than their own, partly, due to male power struggle nature.))

Languages that do not have any “reference” or “object”, or otherwise does not require the programer to have some internal model of source code, are: Mathematica (aka Wolfram Language), most unix shells, PowerShell, and to a large degree PHP, JavaScript. (others may include TCL, Haskell, OCaml.)

For another example of complexity as a consequence of references, see: How to Copy a Nested List in Python? .

For some detail on language design aspects, see: Jargons and High Level Languages and Hardware Modeled Computer Languages .