<div class="gmail_quote">On Fri, Nov 6, 2009 at 06:12, kj <span dir="ltr"><no.email@please.post></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<br>
In Perl one can assign a value to any element of an array, even to<br>
ones corresponding to indices greater or equal than the length of<br>
the array:<br>
<br>
  my @arr;<br>
  $arr[999] = 42;<br>
<br>
perl grows the array as needed to accommodate this assignment.  In<br>
fact one common optimization in Perl is to "pre-grow" the array to<br>
its final size, rather than having perl grow it piecemeal as required<br>
by assignments like the one above:<br>
<br>
  my @arr;<br>
  $#arr = 999_999;<br>
<br>
After assigning to $#arr (the last index of @arr) as shown above,<br>
@arr has length 1,000,000, and all its elements are initialized to<br>
undef.<br>
<br>
In Python the most literal translation of the first code snippet<br>
above triggers an IndexError exception:<br>
<br>
>>> arr = list()<br>
>>> arr[999] = 42<br>
Traceback (most recent call last):<br>
  File "<stdin>", line 1, in <module><br>
IndexError: list assignment index out of range<br>
<br>
In fact, one would need to pre-grow the list sufficiently to be<br>
able to make an assignment like this one.  I.e. one needs the<br>
equivalent of the second Perl snippet above.<br>
<br>
The best I can come up with is this:<br>
<br>
arr = [None] * 1000000<br>
<br>
Is this the most efficient way to achieve this result?<br>
<br>
TIA!<br>
<br>
kynn<br></blockquote><div><br>Is there a reason you need to pre-allocate the list other than the fact that you do it that way in Perl? <br></div></div>