[Baypiggies] One and two dim arrays in Python
Alex Martelli
aleax at google.com
Tue Aug 26 02:52:39 CEST 2008
On Mon, Aug 25, 2008 at 5:00 PM, Nathan Pease <n8pease at yahoo.com> wrote:
> this seems to work:
> a = {}
> for i in range(0, 10): a[i] = 'foo'
Yep, but it builds a *dict* (Pythonese for hashtable), NOT a *list*
(Pythonese for vector/array, more or less) -- so for example the order
of a's items is not guaranteed, etc.
To build a list, the list-comprehension syntax already repeatedly
suggested is generally best -- and the 'something' given in those
examples can perfectly well be an expression, so for example
squares = [i*i for i in range(10)]
works just fine. If each item needs to be computed in some
complicated way, it can be sometimes more readable to use the more
ancient syntax:
a = []
for i in range(10):
a.append(...whatever complicated thing you need...)
The boundary between where it's best to use a list comprehension,
where the more ancient syntax based on .append, is an issue of style,
and more or less spelled out in the Python style guide. However, net
of purely stylistical issues, all of this is spelled out quite
extensively in books such as "Python in a Nutshell" -- I'm biased, of
course, but I would not recommend programming in Python without having
read it (skipping the chapters not of immediate interest;-).
Alex
More information about the Baypiggies
mailing list