
-----------------------------------
mike200015
Thu Jan 24, 2008 10:19 am

Lists - returning all occurences of value
-----------------------------------
Is there a way to return the position of all occurrences of a certain value in a list.  I know there is a built in list function  index() which returns the position of the first occurrence of a given value, but I need to know the position of all occurrences.

-----------------------------------
Nick
Thu Jan 24, 2008 11:14 am

RE:Lists - returning all occurences of value
-----------------------------------
well couldn't you just print your list to see all values?

-----------------------------------
wtd
Thu Jan 24, 2008 12:44 pm

RE:Lists - returning all occurences of value
-----------------------------------
As far as I know there is no built-in method to do this, but it's all of two concise lines of code to define it yourself.

def all_indexes(lst, f):
    return (i for i, x in enumerate(lst) if f(x))

a = [1, 2, 3, 4, 3, 2, 1]

print list(all_indexes(a, lambda x: x == 1))

Outputs:

[0, 6]

-----------------------------------
mike200015
Thu Jan 24, 2008 1:07 pm

Re: Lists - returning all occurences of value
-----------------------------------
yea that would work great!  thanks wtd  :)

-----------------------------------
wtd
Thu Jan 24, 2008 2:42 pm

RE:Lists - returning all occurences of value
-----------------------------------
It's worth asking...  do you understand how the code I posted works?

-----------------------------------
mike200015
Thu Jan 24, 2008 3:10 pm

Re: Lists - returning all occurences of value
-----------------------------------
yea i do after looking over it for a few mins... the only confusing part that i'm not 100% on is the return statement.. looks confusing since its on a single line.  I understand what is being returned, just not clear on how it works as a single line

-----------------------------------
wtd
Thu Jan 24, 2008 4:05 pm

RE:Lists - returning all occurences of value
-----------------------------------
The function is returning a generator object, which is created by the generator expression:

i for i, x in enumerate(lst) if f(x)

Understanding how this works is the key to understanding the magic of this function.

Note that the enumerate function also returns a generator object.

In earlier version of Python we had list comprehensions, and they were good.  

Let's say you have a list:

my_list = [1, 4, 3, 2]

You can transform that into another list like so:

my_other_list = [x * 2 for x in my_list]

At which point you'd have:

[2, 8, 6, 4]

And you can tack on conditionals.

my_other_list = [x * 2 for x in my_list if x * 2 