[Tutor] arrays in Python?
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Mon Mar 8 14:27:53 EST 2004
On Mon, 8 Mar 2004, Christopher Spears wrote:
> What is an array?
Hi Chris,
As with many things, it depends on the definition. There's a terse
definition here:
http://www.nist.gov/dads/HTML/array.html
and there's a more full-fledged entry from the Wikipedia:
http://en.wikipedia.org/wiki/Array
"""An array, also known as a vector or list, is one of the simplest data
structures in computer programming. Arrays hold a fixed number of
equally-sized data elements, generally of the same data type. Individual
elements are accessed by index using a consecutive range of integers, as
opposed to an associative array."""
And that definition should sound similar to something you've already seen:
the Python List fits that description pretty well. Not exactly, but
pretty closely.
Many folks who say "array" will usually restrict the meant to be a
collection of the same data type. That is, some folks will feel slightly
disturbed to see something like:
###
>>> l = ['one', 2, list('three')]
>>> l
['one', 2, ['t', 'h', 'r', 'e', 'e']]
###
because there are three distinct "types" of things in here (strings, ints,
and lists) , and in most languages, it's usually very difficult to write
functions that handle different types.
In Python, those three things can be handled "generically" --- that is,
it's possible to define functions that work on all three types:
###
>>> def double(x): return x + x
...
>>> for x in l:
... print x, double(x)
...
one oneone
2 4
['t', 'h', 'r', 'e', 'e'] ['t', 'h', 'r', 'e', 'e', 't', 'h', 'r', 'e', 'e']
###
However, it's often difficult to write such generic operations for
everything that we want to do. And for the most part, it's often a good
idea to keep lists of a single type.
Please feel free to ask more questions about this. Good luck!
More information about the Tutor
mailing list