Python equivalent of Java Vector

Christopher Browne cbbrowne at news.hex.net
Mon Oct 2 20:38:50 EDT 2000


In our last episode (Mon, 02 Oct 2000 21:19:50 GMT),
the artist formerly known as hoopy_frood at my-deja.com said:
>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."

A Python "dictionary" can certainly be used to handle this; this
provides arbitrary access that does not mandate actually _filling_ any
of the slots in.

<http://www.python.org/doc/current/lib/typesmapping.html>

You might do:
  a[0] = "this"
  a[1] = "that"
  a[7] = "other"

note that a[2] thru a[6] wind up not having any values; if you try to
access them, Python would raise a KeyError exception.

Which means that safely accessing entries requires something like:
  if a.has_key(k):
    do something with a[k]
  else:
    do whatever is needed if there is no a[k]
-- 
(concatenate 'string "cbbrowne" "@" "acm.org")
<http://www.ntlug.org/~cbbrowne/scripting.html>
"Intel engineering seem to have misheard Intel marketing strategy. The
phrase was ``Divide and conquer'' not ``Divide and cock up''"
-- <iialan at www.linux.org.uk> Alan Cox



More information about the Python-list mailing list