[Tutor] Python equivalent of Java Vecor?

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 3 Oct 2000 01:46:16 +0200

On Mon, Oct 02, 2000 at 04:13:42PM -0500, R. A. wrote:
> I've been asked another Python question that's over my head, so I asked
> the querant to re-phrase it a bit so I could ask y'all.  Here is his
> question:
> "Does Python have something equivalent to Java's Vector?  For instance,
> most of the time if you want to use an array you have to declare the
> size up front.  Java has a Vector class which is an array of objects
> which grows as you add things to it.
> "Just curiousity on my part really, but if you are serious about using
> Python productively, you probably need to answer that.  In Java, for
> instance, if I want an array of String I say "String tmp[]=new
> String[5]" and I have an array of Strings with 5 slots.  If I didn't
> know how many Strings I was going to have though, I could say "Vector
> tmp=new Vector()" then every time I wanted to add a String, say "String
> tmpvalue" I could say "tmp.addElement(tmpvalue)".  Then, I could say
> "tmp.size()" to see how many elements were in the Vector, and I can even
> to a "tmp.elementAt(int x)" to retrieve a value.  So, I think the
> terminology would be that Java supports dynamic arrays of objects.  I
> was wondering if Python had the equivalent."

Yes. And Python's is far better. They're usually called lists, they're
first-class citizens so they're supported by language syntax, and they
can hold any kind of object.

tmp = []              # Make tmp a new, empty list
tmp.append(tmpvalue)  # Append tmpvalue to tmp, whatever type it is
len(tmp)              # Returns the number of items in tmp
tmp[3]                # Returns element 3 (numbering starts at 0)
tmp.index("bla")      # Finds the index of "bla", or -1 if it's not in the
                      # list
tmp.sort()            # Sort the list

Et cetera.

Python supports "dynamic arrays of objects" just as well as it supports

Remco Gerlich