numbering variables
Steve
dippyd at yahoo.com
Tue Mar 29 22:12:33 EST 2005
Ron_Adam wrote:
> On Mon, 28 Mar 2005 13:39:17 +0200, remi <remi at non.com> wrote:
>
>>Hello,
>>
>>I have got a list like : mylist = ['item 1', 'item 2',....'item n'] and
>>I would like to store the string 'item1' in a variable called s_1,
>>'item2' in s_2,...,'item i' in 's_i',... The lenght of mylist is finite ;-)
>>Any ideas ?
>>Thanks a lot.
>>RĂ©mi.
>
> Why not just access the list by index? Just start with zero instead
> of 1.
If you _really_ must have one-based indexes, use a
sentinal at the beginning of the list:
>>> mylist = ['item 1', 'item 2',....'item n']
>>> s = [None] + mylist # the sentinal is never used
>>> print s[1]
'item 1'
>>> print s[28]
'item 28'
>>> print s[29] # there are only 28 items!
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
Then you can process all the items without needing to
remember how many there are:
>>> for i in range(1, len(s)):
... do_something(s[i])
--
Steven
More information about the Python-list
mailing list