mutable

Is the use of del bad?

Is the use of del bad? Question: I commonly use del in my code to delete objects: >>> array = [4, 6, 7, ‘hello’, 8] >>> del(array[array.index(‘hello’)]) >>> array [4, 6, 7, 8] >>> But I have heard many people say that the use of del is unpythonic. Is using del bad practice? >>> array …

Total answers: 7

Is making in-place operations return the object a bad idea?

Is making in-place operations return the object a bad idea? Question: I’m talking mostly about Python here, but I suppose this probably holds for most languages. If I have a mutable object, is it a bad idea to make an in-place operation also return the object? It seems like most examples just modify the object …

Total answers: 4

are user defined classes mutable

are user defined classes mutable Question: Say I want to create a class for car, tractor and boat. All these classes have an instance of engine and I want to keep track of all the engines in a single list. If I understand correctly if the motor object is mutable i can store it as …

Total answers: 4

Why does using `arg=None` fix Python's mutable default argument issue?

Why does using `arg=None` fix Python's mutable default argument issue? Question: I’m at the point in learning Python where I’m dealing with the Mutable Default Argument problem. # BAD: if `a_list` is not passed in, the default will wrongly retain its contents between successive function calls def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list # GOOD: if …

Total answers: 5

Why the "mutable default argument fix" syntax is so ugly, asks python newbie

Why the "mutable default argument fix" syntax is so ugly, asks python newbie Question: Now following my series of “python newbie questions” and based on another question. Prerogative Go to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables and scroll down to “Default Parameter Values”. There you can find the following: def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list def good_append(new_item, a_list=None): if a_list …

Total answers: 8

List of lists changes reflected across sublists unexpectedly

List of lists changes reflected across sublists unexpectedly Question: I created a list of lists: >>> xs = [[1] * 4] * 3 >>> print(xs) [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] Then, I changed one of the innermost values: >>> xs[0][0] = 5 >>> print(xs) [[5, 1, 1, 1], …

Total answers: 17