why can’t I change only a single element in a nested list in Python [duplicate]

A strange behaviour indeed, but that’s only because * operator makes shallow copies, in your case – shallow copies of [0, 0, 0] list. You can use the id() function to make sure that these internal lists are actually the same: out=[[0]*3]*3 id(out[0]) >>> 140503648365240 id(out[1]) >>> 140503648365240 id(out[2]) >>> 140503648365240 Comprehensions can be used … Read more

Split a list into nested lists on a value

>>> def isplit(iterable,splitters): return [list(g) for k,g in itertools.groupby(iterable,lambda x:x in splitters) if not k] >>> isplit(L,(None,)) [[1, 4], [6, 9], [3, 9, 4]] >>> isplit(L,(None,9)) [[1, 4], [6], [3], [4]] benchmark code: import timeit kabie=(“isplit_kabie”, “”” import itertools def isplit_kabie(iterable,splitters): return [list(g) for k,g in itertools.groupby(iterable,lambda x:x in splitters) if not k] “”” ) … Read more

Function changes list values and not variable values in Python [duplicate]

Python variables contain pointers, or references, to objects. All values (even integers) are objects, and assignment changes the variable to point to a different object. It does not store a new value in the variable, it changes the variable to refer or point to a different object. For this reason many people say that Python … Read more