what is the python equivelant of this?

Alex Martelli aleaxit at yahoo.com
Fri Oct 13 07:37:34 EDT 2000


"Mats Kindahl" <matkin at iar.se> wrote in message
news:umd7h5q9k2.fsf at iar.se...
> Neil Schemenauer <nas at arctrix.com> writes:
>
> [snip]
>
> > > or how about
> > >
> > > RECORD* recordarray = malloc( sizeof(RECORD) * 10 );
> > > memset( recordarray0, sizeof(RECORD) * 10 );
> >
> > What is recordarry0?  Maybe something like this is what you want:
> >
> >     recordarray = []
> >     for i in range(10):
> >         recordarray.append(Record(10, "gumby"))
>
> I'm new to Python, but is there anything wrong with:
>
> recordarray = [0] * 10

Absolutely nothing wrong -- this makes 'recordarray' refer
to a list of ten zeros (not to a list of ten "empty" things
of "RECORD" type, which seems more similar to what was
requested by the original poster).

Assuming you have defined a "class Record", which, when
called without arguments, returns an "empty" thing of the
type we desire, then, there is a difference between:

recordarray = [Record()] * 10

this makes 'recordarray' refer to a list of ten references
to ONE AND THE SAME "empty thing of Record type"; it's
unlikely this is what one wants in this case...

recordarray = [Record() for i in range(10)]

this makes 'recordarray' refer to a list of ten references
to ten DIFFERENT "empty things of Record type", and I
think this is more likely to be what is wanted.  *NOTE*:
the latter syntax only works in Python 1.6 and later; to
get a similar effect under older Python versions, you
do need the wordier already-suggested syntax:
    recordarray = []
    for i in range(10):
        recordarray.append(Record())
or variations such as:
    recordarray = [None] * 10
    for i in range(10):
        recordarray[i]=Record()


Alex







More information about the Python-list mailing list