Advertisement
nanenj

For Each w/ Index

Jun 24th, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. # Lists in Python are frequently used, one task that's frequently needed
  2. # is to iterate over a list and retrieve the index of each item in the list
  3. # in Python, this may not as straight-forward as you would be used to in
  4. # some other languages.  We're going to use the sample list below to
  5. # demonstrate a few ways of accomplishing this.
  6. animals = ["Dog", "Cat", "Bird", "Fish"]
  7.  
  8. # The idiomatic way to do this in Python is with the enumerate function
  9. # https://docs.python.org/3/library/functions.html#enumerate
  10. print("For Each w/ enumerate():")
  11. for index, item in enumerate(animals):
  12.   print("Index : " + str(index) + "\nAnimal: " + item + "\n")
  13.  
  14. # Example Output:
  15. # For Each w/ enumerate():
  16. # Index : 0
  17. # Animal: Dog
  18. #
  19. # Index : 1
  20. # Animal: Cat
  21. #
  22. # Index : 2
  23. # Animal: Bird
  24. #
  25. # Index : 3
  26. # Animal: Fish
  27.  
  28. # Often, people seeking a more direct analog to what they're used to, might end up with
  29. # something closer to the following using the range and len functions.  Many people come across
  30. # this solution from Google.
  31. # ex: http://hplgit.github.io/primer.html/doc/pub/looplist/._looplist-solarized003.html
  32. print("For Each w/ range(len()):")
  33. for index in range(len(animals)):
  34.   print("Index : " + str(index) + "\nAnimal: " + animals[index] + "\n")
  35.  
  36. # Example Output:
  37. # For each, w/ range(len()):
  38. # Index : 0
  39. # Animal: Dog
  40. #
  41. # Index : 1
  42. # Animal: Cat
  43. #
  44. # Index : 2
  45. # Animal: Bird
  46. #
  47. # Index : 3
  48. # Animal: Fish
  49.  
  50.  
  51. # As well, the more direct port of a for loop in a language that doesn't have proper
  52. # enumerables is even demonstrated in the documentation for the enumerate function
  53. print("For each, w/ manual indexing:")
  54. index = 0
  55. for animal in animals:
  56.   print("Index : " + str(index) + "\nAnimal: " + animal + "\n")
  57.   index += 1
  58.  
  59. # Example Output:
  60. # For each, w/ manual indexing:
  61. # Index : 0
  62. # Animal: Dog
  63. #
  64. # Index : 1
  65. # Animal: Cat
  66. #
  67. # Index : 2
  68. # Animal: Bird
  69. #
  70. # Index : 3
  71. # Animal: Fish
  72.  
  73. # Note that enumerate returns each item as a tuple.  You can see this in action by creating a list
  74. # out of the returned items.
  75. new_list = list(enumerate(animals))
  76. print(str(new_list)) # => [(0, 'Dog'), (1, 'Cat'), (2, 'Bird'), (3, 'Fish')]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement