Pythonic way to default loop counters

Richard Neumann

I sometimes use generators to filter for certain values in programs and want to log the filtered items.
Let's assume:

def filter_items(items):
    for item in items:
        if item.is_wanted():
            yield item

def process_items(items):
    for item in filter_items(items):
        item.do_stuff()

Now my problem is that I want to log, how many of the filtered items were actually invoked.
Currently I do this:

def process_items(items):
    for count, item in enumerate(filter_items(items)):
        item.do_stuff()

    try:
        count += 1
    except UnboundLocalError:
        count = 0

    print('Processed', count, 'items.')

Now I have the feeling, that checking for an UnboundLocalError is a bit weird, so I considered defaulting the counter instead:

def process_items(items):
    count = -1

    for count, item in enumerate(filter_items(items)):
        item.do_stuff()

    print('Processed', count + 1, 'items.')

However also setting the default counter to -1 also looks weird, since the actual default value on no iteration will be 0. However I cannot default it to 0 because then I could not distinguish between the default value (if no element was iterated) or whether one element was iterated over.

Is there a best-practice or guideline regarding the defaulting of loop counters in Python?

Dimitris Fasarakis Hilliard

I don't think a best practice exists. What I would do (in order to not initialize to -1 and then need to do count + 1) is set the enumerate's start value to 1:

def process_items(items):
    count = 0    
    for count, item in enumerate(filter_items(items), start=1):
        item.do_stuff()

    print('Processed', count, 'items.')

this makes it clear to me what's going on. (Note that start=1 can just be written 1).

Note that yes, this isn't the most explicit way to do this (see Stefan's answer). Since you do know about the fact that the for loop targets are visible after the loop, you should be ok.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Pythonic way to calculate the mean and variance of values in Counters

From Dev

Pythonic way to "default" a conditional statement?

From Java

Pythonic way to combine FOR loop and IF statement

From Dev

Pythonic way to loop over dictionary

From Dev

Pythonic way to break out of loop

From Dev

What is the pythonic way to to resume a loop within a loop

From Dev

Pythonic way to overwrite a default argument with **kwargs?

From Dev

how to change for loop code to pythonic way

From Dev

Pythonic way to make dictionary within a for loop

From Dev

Pythonic way to detect final iteration of a loop

From Dev

Pythonic way of handling two statements in a for loop?

From Java

What is the pythonic way to detect the last element in a 'for' loop?

From Dev

Pythonic way to replace > with < in the midst of a big for loop

From Dev

Pythonic way of executing a loop on a dictionary of lists

From Dev

Pythonic way to join a string in a loop to create textblock

From Dev

Is there a more pythonic way of writing a loop that modifies a list?

From Dev

Is there a pythonic way for loop and use previous item

From Dev

Pythonic way of checking parameter is an integer and setting a default value if no parameter

From Java

What is the pythonic way to avoid default parameters that are empty lists?

From Dev

Pythonic way to initialize an object with a lot of parameters and default value

From Dev

Unable to reset counters in for loop

From Dev

For X of Y loop counters

From Dev

(Python) multiple counters in a for loop?

From Dev

Is there are more pythonic way to write a while loop that only updates a variable?

From Dev

What is the most pythonic way to create a 'For Loop' that filters through a dictionary?

From Dev

How to stop code execution of for loop from try/except in a Pythonic way?

From Dev

What is the pythonic way of running an asyncio event loop forever?

From Dev

Pythonic way of splitting loop over list in two parts with one iterator

From Dev

Pythonic way to broadcast/loop through values when expanding kwargs

Related Related

  1. 1

    Pythonic way to calculate the mean and variance of values in Counters

  2. 2

    Pythonic way to "default" a conditional statement?

  3. 3

    Pythonic way to combine FOR loop and IF statement

  4. 4

    Pythonic way to loop over dictionary

  5. 5

    Pythonic way to break out of loop

  6. 6

    What is the pythonic way to to resume a loop within a loop

  7. 7

    Pythonic way to overwrite a default argument with **kwargs?

  8. 8

    how to change for loop code to pythonic way

  9. 9

    Pythonic way to make dictionary within a for loop

  10. 10

    Pythonic way to detect final iteration of a loop

  11. 11

    Pythonic way of handling two statements in a for loop?

  12. 12

    What is the pythonic way to detect the last element in a 'for' loop?

  13. 13

    Pythonic way to replace > with < in the midst of a big for loop

  14. 14

    Pythonic way of executing a loop on a dictionary of lists

  15. 15

    Pythonic way to join a string in a loop to create textblock

  16. 16

    Is there a more pythonic way of writing a loop that modifies a list?

  17. 17

    Is there a pythonic way for loop and use previous item

  18. 18

    Pythonic way of checking parameter is an integer and setting a default value if no parameter

  19. 19

    What is the pythonic way to avoid default parameters that are empty lists?

  20. 20

    Pythonic way to initialize an object with a lot of parameters and default value

  21. 21

    Unable to reset counters in for loop

  22. 22

    For X of Y loop counters

  23. 23

    (Python) multiple counters in a for loop?

  24. 24

    Is there are more pythonic way to write a while loop that only updates a variable?

  25. 25

    What is the most pythonic way to create a 'For Loop' that filters through a dictionary?

  26. 26

    How to stop code execution of for loop from try/except in a Pythonic way?

  27. 27

    What is the pythonic way of running an asyncio event loop forever?

  28. 28

    Pythonic way of splitting loop over list in two parts with one iterator

  29. 29

    Pythonic way to broadcast/loop through values when expanding kwargs

HotTag

Archive