objects in a list ...

Alex Martelli aleax at aleax.it
Mon Jul 15 08:44:51 EDT 2002


Ingo Stöcker wrote:

> Hey.
> 
> I am a newbee @ python. For a little application-project I have a
> questions to you:
> 
> I want to create many Objects of a class designed by my own and these
> objects should be stored/append in/on a list. Is this possible and how can
> I realize it? Thanx & Sorry for my bas englisch :-)

Sure, it's perfectly possible.  For example:

class Object(object):
    " insert your class's body here "

alist = []     # an initially-empty list

# make a new one and contextually append it
alist.append(Object())

# make one, then separately append it
anobj = Object()
alist.append(anobj)

# make seven more then append them
alist.extend([ Object() for j in range(7) ])

# make a new one and put it in first place for a change
alist.insert(Object())


and so on, and so forth.  In Python, just about everything
is "first-class" -- you can always hold things in lists or
tuples, or as values in dictionaries, pass them as function
arguments, return them as function results -- no problem.


Alex




More information about the Python-list mailing list