0

It's always bugged me how it seems that the only way to find out where you are inside a for loop is to use a counter. For instance, suppose you want to iterate through a list, and print every entry on a second line, but for the second-to-last entry you also want to print "Fish sticks" after the entry. This is the best way I know of to do this:

counter = 0
for entry in fishSticksList:
   print entry,
   if counter == len(fishSticksList) - 2:
      print "Fish sticks"
   else:
      print ""
   counter += 1

Now, that's not all that bad, but it irks me that it requires a counter variable. I doubt it, but is there any way to do this without creating a counter?

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by vegaseat
0

You could use enumerate() to index the list entries ...

fishSticksList = [1, 2, 3, 4, 5]

for ix, entry in enumerate(fishSticksList):
   print entry,
   if ix == len(fishSticksList) - 2:
      print "Fish sticks"
   else:
      print ""
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.