how to get the ordinal number in list

Rustom Mody rustompmody at gmail.com
Sun Aug 10 14:00:33 EDT 2014


Pressed Send to early.

On Sunday, August 10, 2014 11:15:03 PM UTC+5:30, Rustom Mody wrote:
> >>> # Works the same (SEEMINGLY)

> ... # Now change the return to an yield
> ... 
> >>> def search(x,y):    
> ...    for id ,value in enumerate(x):
> ...        if y==value : yield id
> ... 
> >>> search(["x1","x2","x3", "x2", "x5", "x2"], "x2")
> >>> # Hmm wazzat?!
> ... list(search(["x1","x2","x3", "x2", "x5", "x2"], "x2"))
> [1, 3, 5]

Now you can of course use that to print if you choose

>>> for x in search(["x1","x2","x3"], "x2"):
...   print x
1


But you can also put some other possibly more complex and useful action there
in place of the print if you choose.

With the print version that's not an option.



More information about the Python-list mailing list