I have the need to make @ted's answer (imo) more readable and to add some explanations.
Tidied up solution:
# Function to print the index, if the index is evenly divisable by 1000:
def report(index):
if index % 1000 == 0:
print(index)
# The function the user wants to apply on the list elements
def process(x, index, report):
report(index) # Call of the reporting function
return 'something ' + x # ! Just an example, replace with your desired application
# !Just an example, replace with your list to iterate over
mylist = ['number ' + str(k) for k in range(5000)]
# Running a list comprehension
[process(x, index, report) for index, x in enumerate(mylist)]
Explanation: of enumerate(mylist)
: using the function enumerate
it is possible to have indices in addition to the elements of an iterable object (cf. this question and its answers). For example
[(index, x) for index, x in enumerate(["a", "b", "c"])] #returns
[(0, 'a'), (1, 'b'), (2, 'c')]
Note: index
and x
are no reserved names, just names I found convenient - [(foo, bar) for foo, bar in enumerate(["a", "b", "c"])]
yields the same result.