how to get the ordinal number in list

Chris Angelico rosuav at gmail.com
Fri Aug 8 22:46:43 EDT 2014


On Sun, Aug 10, 2014 at 3:35 AM, luofeiyu <elearn2014 at gmail.com> wrote:
>>>> x=["x1","x3","x7","x5","x3"]
>>>> x.index("x3")
> 1
> if i want the result of 1 and 4 ?

Want to know what you can do with some object? Try this:

>>> help(x)

In this case, though, I suspect there's no built-in to search for
*all* of the occurrences of something, so you're best doing your own
loop. You can either iterate straight over the list with enumerate, as
you were doing, or you can use index() with its start argument:

>>> def find_all(lst, obj):
    indices = [-1]
    try:
        while True:
            indices.append(lst.index(obj, indices[-1]+1))
    except ValueError:
        return indices[1:]

>>> x=["x1","x3","x7","x5","x3"]
>>> find_all(x, "x3")
[1, 4]

It's probably cleaner to just iterate over the list once, though, and
you already know how to do that.

ChrisA



More information about the Python-list mailing list