immutability

Unexpected Behavior of Extend with a list in Python

Unexpected Behavior of Extend with a list in Python Question: I am trying to understand how extend works in Python and it is not quite doing what I would expect. For instance: >>> a = [1, 2, 3] >>> b = [4, 5, 6].extend(a) >>> b >>> But I would have expected: [4, 5, 6, …

Total answers: 5

Immutable numpy array?

Immutable numpy array? Question: Is there a simple way to create an immutable NumPy array? If one has to derive a class from ndarray to do this, what’s the minimum set of methods that one has to override to achieve immutability? Asked By: NPE || Source Answers: You can make a numpy array unwriteable: a …

Total answers: 3

How to make an immutable object in Python?

How to make an immutable object in Python? Question: Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can’t just override __setattr__, because then you can’t even set attributes in the __init__. Subclassing a tuple is a trick that works: class Immutable(tuple): …

Total answers: 26

Check for mutability in Python?

Check for mutability in Python? Question: Consider this code: a = {…} # a is an dict with arbitrary contents b = a.copy() What role does mutability play in the keys and values of the dicts? How do I ensure changes to keys or values of one dict are not reflected in the other? How …

Total answers: 7

Remove specific characters from a string in Python

Remove specific characters from a string in Python Question: I’m trying to remove specific characters from a string using Python. This is the code I’m using right now. Unfortunately it appears to do nothing to the string. for char in line: if char in ” ?.!/;:”: line.replace(char,”) How do I do this properly? Asked By: …

Total answers: 26

What would a "frozen dict" be?

What would a "frozen dict" be? Question: A frozen set is a frozenset. A frozen list could be a tuple. What would a frozen dict be? An immutable, hashable dict. I guess it could be something like collections.namedtuple, but that is more like a frozen-keys dict (a half-frozen dict). Isn’t it? A “frozendict” should be …

Total answers: 14

Hashable, immutable

Hashable, immutable Question: From a recent SO question (see Create a dictionary in python which is indexed by lists) I realized I probably had a wrong conception of the meaning of hashable and immutable objects in python. What does hashable mean in practice? What is the relation between hashable and immmutable? Are there mutable objects …

Total answers: 9

Why are python strings and tuples are made immutable?

Why are python strings and tuples are made immutable? Question: I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable? Asked By: user186477 || Source Answers: One is performance: knowing that a string is immutable makes it easy to lay it out …

Total answers: 6