s.index(x[, i[, j]]) will change the s ?

tec technic.tec at gmail.com
Thu Sep 10 01:47:14 EDT 2009


s7v7nislands 写道:
> Thanks for your reply! Sorry for my poor english!
> 
> On Sep 10, 12:33 pm, Chris Rebert <c... at rebertia.com> wrote:
>> On Wed, Sep 9, 2009 at 9:00 PM, s7v7nislands<s7v7nisla... at gmail.com> wrote:
>>> hi all:
>>>    what is the s.index() mean? does the index() change the s?
>> It tells you the index of the first instance of the given element in
>> the sequence. Or, to quote the docs:
>>     s.index(x[, i[, j]]) --- return smallest k such that s[k] == x and
>> i <= k < j
>>
>> No, .index() does not modify the sequence itself.
> 
> I known index() does not modify the sequence itself. my question is so
> why the doc put the index() method in the mutable sequence types list?
It applies to both mutable and immutable sequence.

>>>    In python2.6 doc (6.6.4. Mutable Sequence Types), Note 4:
>>> Raises ValueError when x is not found in s. When a negative index is
>>> passed as the second or third parameter to the index() method, the
>>> list length is added, as for slice indices. If it is still negative,
>>> it is truncated to zero, as for slice indices.
>>> Changed in version 2.3: Previously, index() didn’t have arguments for
>>> specifying start and stop positions.
>> Nothing in the above says anything about modifying a sequence...
> When a negative index is passed as the second or third parameter to
> the index() method, the list length is added, as for slice indices.
> I don't understand the mean.  the list length is added, why? if it
> changed, the original will change ?
It is just the common rule for negative index.
eg. s[-k] == s[-k + len(s)].
The original sequence is not changed.

>>> who can give a example?  and why the s.remove() also point to note 4?
>> Because it has the same behavior when the item is not present in the sequence.
>>
>> Examples using lists:
>>
>> assert ["c", "a", "b", "c", "c"].index("c", 1) == 3
>>
>> try:
>>     ["a", "b"].index("c")
>> except ValueError:
>>     print "'c' was not in the list"
>> else:
>>     raise RuntimeError, "Should never get here"
>>
>> x = ["a", "b", "c"]
>> x.remove("b")
>> assert len(x) == 2 and x[0] == "a" and x[1] == "c"
> I want a example, maybe: use the a negative index is passed as the
> second or third parameter, and see the length changed.
x = 'abcde'
x.index('d', -3, -1) = x.index('d', 2, 4) = 3
x.index('a', -3, -1) = x.index('a', 2, 4) = -1, raise ValueError

>>> Is the document wrong?
>> No. What made you think so?
> Sorry for my poor english. do you understand me now? thanks!
>> Cheers,
>> Chris
>> --http://blog.rebertia.com
> 



More information about the Python-list mailing list