Building lists
Larry Hudson
orgnut at yahoo.com
Tue Oct 21 03:11:38 EDT 2014
On 10/20/2014 12:49 PM, Seymore4Head wrote:
> On Mon, 20 Oct 2014 20:40:18 +0100, MRAB <python at mrabarnett.plus.com>
> wrote:
<snip>
> Do you have to know the number of items the list will have before
> making it?
>
No, it is not necessary, lists are NOT the same as arrays in other languages. But it IS
possible to create an initial list of a specific size:
myList = [None] * 50
That creates a 50-element list with each element set to None. (BTW, the indexes are from 0-49,
not 0-50.) I have found this occasionally useful, but I'll emphasize, it's only RARELY useful.
The .append() method is far more versatile.
As to your original problem: my question to you is what is your purpose?
1) To solve this particular problem, using Python.
or
2) To explore the usage of lists, applying them to this problem.
If your purpose is the first, then I agree with the advice you have already been given here.
Dictionaries are a much better fit to this problem.
If your purpose is the second, then go ahead and use this for your exploration. But realize
that to more experienced Pythonistas this would be a very un-pythonic approach. Even better
would be to try multiple approaches -- lists, dictionaries, lists with dictionaries,
dictionaries with lists or tuples... And any other combinations you can come up with. This
will give you even more experience, and allow you to evaluate the different approaches.
And no, I will not give you a ready-made "canned" answer. For one thing, your description is
too vague to effectively do that. Good luck.
-=- Larry -=-
More information about the Python-list
mailing list