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?

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 ""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.