code_junkie

In Python, how do I find the index of an item given a list containing it?

Nov 11th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.49 KB | None | 0 0
  1. >>> ["foo","bar","baz"].index('bar')
  2.  
  3. >>> help(["foo", "bar", "baz"])
  4. Help on list object:
  5.  
  6. class list(object)
  7. ...
  8.  
  9. |
  10. | index(...)
  11. | L.index(value, [start, [stop]]) -> integer -- return first index of value
  12. |
  13.  
  14. def all_indices(value, qlist):
  15. indices = []
  16. idx = -1
  17. while 1:
  18. try:
  19. idx = qlist.index(value, idx+1)
  20. indices.append(idx)
  21. except ValueError:
  22. break
  23. return indices
  24.  
  25. all_indices("foo", ["foo","bar","baz","foo"])
Add Comment
Please, Sign In to add comment