Is 'everything' a refrence or isn't it?

Dan Sommers me at privacy.net
Thu Jan 5 12:39:02 CET 2006


On Wed, 04 Jan 2006 22:38:06 -0500,
"Stuart D. Gathman" <stuart at bmsi.com> wrote:

> On Wed, 04 Jan 2006 10:54:17 -0800, KraftDiner wrote:
>> I was under the assumption that everything in python was a refrence...
>> 
>> so if I code this:
>> lst = [1,2,3]
>> for i in lst:
>> if i==2:
>> i = 4
>> print lst
>> 
>> I though the contents of lst would be modified.. (After reading that
>> 'everything' is a refrence.)
>> ...
>> Have I misunderstood something?

> It might help to do a translation to equivalent C:

> int _i1 = 1;
> int _i2 = 2;
> int _i3 = 3;
> int _i4 = 4;
> int* lst[NLST] = { &_i1,&_i2,&_i3 };

Okay so far.

> int _idx;	/* internal iterator */
> for (_idx = 0; _idx < NLST; ++_idx) {
>   int *i = lst[_idx];

[snip]

That's the C idiom

    for i in range(len(lst))

we all complain about here.  How about (untested):

/*
iterate over the list, binding i to each item in succession;
_idx is internal to the interpreter;
separate the definition of i from the assignment of i for clarity
*/

int **_idx;
for( _idx = lst; _idx < lst + NLST; ++_idx ) {
    int *i;
    i = *_idx;

    /* compare "the item to which i is bound" to "a constant" */
    if( *i == *(&_i2) )
        /* rebind i to _i4 */
        i = &_i4;
}

> for (_idx = 0; _idx < NLST; ++_idx)
>   printf("%d\n",*lst[_idx]);

for( _idx = lst; _idx < lst + NLST; ++_idx ) {
    int *i = *_idx;
    printf( "%d\n", *i );
}

Regards,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>



More information about the Python-list mailing list