Avoiding referencing (was: Python sequences reference - problem?)
Thorsten Kampe
thorsten at thorstenkampe.de
Fri Sep 20 03:49:58 EDT 2002
* Alex Martelli
> Just remembed that EVERYTHING works by reference, and what
> could possibly be the problem...?
The problem is that we newbies sometimes don't want referencing:
#v+
def part(seq, indices):
""" chop seq by indices """
partition = []
for slice in indices:
partition.append(seq[:slice])
del seq[:slice]
partition.append(seq)
return partition
#v-
>>> foo = [11, 22, 33, 44, 55, 66, 77]
>>> part(foo, [2, 3])
[[11, 22], [33, 44, 55], [66, 77]] # yes
>>> foo
[66, 77] # aaarrrghhh
Obviously I did not pass 'foo' "by value" to function 'part' but by
reference and obviously not only local variable 'seq' was modified in
the function but "outer" variable 'foo', too.
So how to deal with that?
1. "Just don't call function 'part' by with a variable, call it by
value - part([11, 22, 33, 44, 55, 66, 77], [2, 3]) - and everything's
okay".
Obviously no solution to me.
2. "If you don't want referencing, call it with a copy of 'foo' like:
part(foo[:], [2, 3])"
Yes, but how do I know in advance that 'part' modifies 'foo'? I might
not be the author of 'part'.
3. "Rewrite function 'part' so that it works with a tuple as argument.
Thereby you're avoiding all possible modifying of existing objects."
Yes, but I'm also losing the "extended" possibilities of lists:
"list.append", "list.reverse", "list.index" etc. My code will be twice
as long as it would be with list methods.
Is there a way to "bypass" referencing _without_ disadvantages? I'm
sure there is a "canonical" way to do this in Python!
Thorsten
More information about the Python-list
mailing list