Skip to main content

A list of python utilities

Project description

Some personal Python utilities. Only uses standard library.

Gotchas

Dictionaries

What is the difference between

dict1 = dict(zip(["a", "b", "c"], [[]] * 3))

and

dict2 = {key:[] for key in ["a", "b", "c"]}

When you print them, both return

{'a': [], 'b': [], 'c': []}

But try, for example,

dict1["a"].append(1)
print(dict1)
dict2["a"].append(1)
print(dict2)

Surprisingly, you get

dict1 = {'a': [1], 'b': [1], 'c': [1]}
dict2 = {'a': [1], 'b': [], 'c': []}

What happened here? The empty lists in dict1 are actually the same list, so when you change one, you change all of them. You can run into the same trap if you initialize a dictionary with

dict.fromkeys(["a", "b", "c"], [])

or if you pass in a mutable object as a default argument to a function.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pycutils-0.0.4.tar.gz (3.2 kB view hashes)

Uploaded Source

Built Distribution

pycutils-0.0.4-py3-none-any.whl (3.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page