0

I have a list that I am going through using list comprehension. Each time I get a a value from the list, I want to output where I currently am in the list.

So if a list has 5 items, the output would be something like this (Including my code for the list comp):

values = ['a', 'b', 'c', 'd', 'e']
modded_values = [print(val.upper()) for val in values]

So the output from print would be:

(1/5)A
(2/5)B
(3/5)C
...

I made a small function (which doesn't work), as the variable value starts from 0 each time the function is called.

def counter(l):
    list_length = len(l)
    current = +1
    return '(' + str(current) + '/' + str(list_length) + ')'

Which would be used like this:

values = ['a', 'b', 'c', 'd', 'e']
modded_values = [print(counter(values)+val.upper()) for val in values]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ChaChaPoly
  • 1,811
  • 5
  • 17
  • 39
  • 1
    Why are you using a list comprehension to call the `print()` function? You'll get lists with `None` objects, almost certainly useless for any other code. – Martijn Pieters Oct 31 '16 at 14:37
  • 1
    Use the `enumerate()` function to add a counter to a `for` loop. If you are not producing a list (you appear to be producing *output to `stdout`* instead), then use a normal `for` loop, not a list comprehension. – Martijn Pieters Oct 31 '16 at 14:38
  • @MartijnPieters Could you give me an example? I am not really using print, I am using a custom function which takes an input value prints it, and also returns the value, that way I can use the values returned and output to stdout at the same time. – ChaChaPoly Oct 31 '16 at 14:40
  • Why do that at all? Why not just use the list after it is built to print results? `print(*list, sep='\n')` would print a list object with each element on a separate line. I've duplicated you to the canonical 'how to count in a loop' question. – Martijn Pieters Oct 31 '16 at 14:41
  • @MartijnPieters It's not the same though. My code takes a long time to run as it makes requests to a webserver. For security reasons I am not able to post the real code, so I dumbed it down, but the priciple is the same. Because it takes to long, I would like to see how far down the list the code is, instead of waiting blindly for it to finish having no idea where it currently is in the looop – ChaChaPoly Oct 31 '16 at 14:43
  • Is it that hard to adapt the examples in that question to your situation? All you are doing is add one more target in the `for` loop, and the `enumerate()` function. – Martijn Pieters Oct 31 '16 at 14:44

0 Answers0