Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Lists in Python are frequently used, one task that's frequently needed
- # is to iterate over a list and retrieve the index of each item in the list
- # in Python, this may not as straight-forward as you would be used to in
- # some other languages. We're going to use the sample list below to
- # demonstrate a few ways of accomplishing this.
- animals = ["Dog", "Cat", "Bird", "Fish"]
- # The idiomatic way to do this in Python is with the enumerate function
- # https://docs.python.org/3/library/functions.html#enumerate
- print("For Each w/ enumerate():")
- for index, item in enumerate(animals):
- print("Index : " + str(index) + "\nAnimal: " + item + "\n")
- # Example Output:
- # For Each w/ enumerate():
- # Index : 0
- # Animal: Dog
- #
- # Index : 1
- # Animal: Cat
- #
- # Index : 2
- # Animal: Bird
- #
- # Index : 3
- # Animal: Fish
- # Often, people seeking a more direct analog to what they're used to, might end up with
- # something closer to the following using the range and len functions. Many people come across
- # this solution from Google.
- # ex: http://hplgit.github.io/primer.html/doc/pub/looplist/._looplist-solarized003.html
- print("For Each w/ range(len()):")
- for index in range(len(animals)):
- print("Index : " + str(index) + "\nAnimal: " + animals[index] + "\n")
- # Example Output:
- # For each, w/ range(len()):
- # Index : 0
- # Animal: Dog
- #
- # Index : 1
- # Animal: Cat
- #
- # Index : 2
- # Animal: Bird
- #
- # Index : 3
- # Animal: Fish
- # As well, the more direct port of a for loop in a language that doesn't have proper
- # enumerables is even demonstrated in the documentation for the enumerate function
- print("For each, w/ manual indexing:")
- index = 0
- for animal in animals:
- print("Index : " + str(index) + "\nAnimal: " + animal + "\n")
- index += 1
- # Example Output:
- # For each, w/ manual indexing:
- # Index : 0
- # Animal: Dog
- #
- # Index : 1
- # Animal: Cat
- #
- # Index : 2
- # Animal: Bird
- #
- # Index : 3
- # Animal: Fish
- # Note that enumerate returns each item as a tuple. You can see this in action by creating a list
- # out of the returned items.
- new_list = list(enumerate(animals))
- print(str(new_list)) # => [(0, 'Dog'), (1, 'Cat'), (2, 'Bird'), (3, 'Fish')]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement