N
Neal Becker
I see list has index member, but is there an index function that applies to
any sequence type?
If not, shouldn't there be?
any sequence type?
If not, shouldn't there be?
Neal said:I see list has index member, but is there an index function that applies to
any sequence type?
If not, shouldn't there be?
Neal said:I see list has index member, but is there an index function that applies
to any sequence type?
If not, shouldn't there be?
Stefan Behnel said:def find_index(seq, value):
try:
find_index = seq.index
except AttributeError:
def find_index(value):
for i,v in enumerate(seq):
if v == value: return i
raise ValueError("index(seq, x): x not in sequence")
return find_index(value)
Looks like an oversight to me as well, yes. The only "difficult"
implementation would be the one for xrange, because you can't search but
must compute the result - but that should be trivial.
Tuples are worse: they implement
__contains__ but not index. So you can say:
py> 2 in (1,2,4,8)
True
but not:
py> (1,2,4,8).index(2)
Tuples are worse: they implement
__contains__ but not index. So you can say:
py> 2 in (1,2,4,8)
True
but not:
py> (1,2,4,8).index(2)
You must be using an old version of Python like 2.5 ;-)
As of yesterday, Py2.6 has tuple.index() and tuple.count().
Python 2.6a0 (trunk:60638M, Feb 6 2008, 18:10:45)
[GCC 4.1.1 (Gentoo 4.1.1)] on linux21
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.