references/addrresses in imperative languages

Xah Lee xah at xahlee.org
Sun Jun 19 18:34:21 EDT 2005


in coding Python yesterday, i was quite stung by the fact that lists
appened to another list goes by as some so-called "reference". e.g.

t=range(5)
n=range(3)
n[0]='m'
t.append(n)
n[0]='h'
t.append(n)
print t


in the following code, after some 1 hour, finally i found the solution
of h[:]. (and that's cheating thru a google search)

def parti(l,j):
    '''parti(l,j) returns l partitioned with j elements per group. If j
is not a factor of length of l, then the reminder elements are dropped.
    Example: parti([1,2,3,4,5,6],2) returns [[1,2],[3,4],[5,6]]
    Example: parti([1,2,3,4,5,6,7],3) returns [[1,2,3],[4,5,6]]'''
    n=len(l)/j
    r=[] # result list
    h=range(j) # temp holder for sublist
    for n1 in range(n):
        for j1 in range(j):
            h[j1]=l[n1*j+j1]
        r.append( h[:] )
    return r

interesting that a dictionary has copy method, but not list. (the pain
is coupled with the uselessness of the Python doc)

------
Btw, behavior such as this one, common in imperative languages and info
tech industry, is a criminality arose out of hacks C, Unix, and from
there all associated imperative langs. (C++, csh, perl, Java... but
each generation improves slightly)

The gist of the matter is that these behaviors being the way they are
really is because they are the easiest, most brainless implementation,
as oppose to being a design decision.

In hindsight analysis, such language behavior forces the programer to
fuse mathematical or algorithmic ideas with implementation details. A
easy way to see this, is to ask yourself: how come in mathematics
there's no such thing as "addresses/pointers/references".

---------

PS is there any difference between
t=t+[li]
t.append(li)

---------
References:

for a analysis of the same situation in Java, see
http://xahlee.org/java-a-day/assign_array_to_list.html

How to write a tutorial
http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html

 Xah
 xah at xahlee.orghttp://xahlee.org/




More information about the Python-list mailing list