Python – Enumerate Lists in a Loop

Plenty of times, when you are looping with a for-each loop in python, you somehow realize that you need a counter. Then you most probably write something ugly like this one:

Why is this ugly? Mainly because the next time when you need a counter in the loop, you either need a new variable or you should remember to set this one to 0. And because using a new variable makes the code look bad, especially if you can avoid it.

If you want to count the trees, you might need enumerator in Python. Or not.

What can you do, to avoid that additional variable?

Well, here comes the python enumerate() feature, that takes a list and returns an enumerate object out of it. And if you loop through that enumerate object, you receive a tuple – the index and the list item itself.

It gets even better – if you only need the index item, you may access the count_value by its index – 0 is for the count, 1 is for the value:

But who likes working with indices, when this can be avoided? Unpacking in the loop does the magic:

As an additional feature, you may also decide to start by an arbitrary index, 100 in this case.

That’s all! 🙂

Tagged with: , , , ,