Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would a pythonista code the equivalent of the ++ increment operator in Python 3?

I am trying to find the right way in Python to accomplish the following task (which doesn't work as written):

myList = ["a", "b", "c"]
myCounter = 5

for item in myList:
  print("""Really long text 
in which I need to put the next iteration of myCounter (""", myCounter++, """) followed 
by a lot more text with many line breaks
followed by the next iteration of myCounter (""", myCounter++, """) followed by even
more long text until finally we get to the next
iteration of the for loop.""", sep='')

Unfortunately (for me at least), the ++ operator or statement doesn't exist in Python as a way to increment a variable by 1, but using

myCounter += 1

in its place doesn't seem work either when I want to print the variable and increment it at the same time. I want it to print 5 and 6 for the first time through the for loop, then 7 and 8 the next time through, then 9 and 10 the last time through. How should this be done in Python 3?

like image 515
Rusty Lemur Avatar asked Mar 15 '23 19:03

Rusty Lemur


1 Answers

I might consider using itertools.count:

import itertools

myCounter = itertools.count(5)
for item in myList:
    print("la la la.", next(myCounter), "foo foo foo", next(myCounter))

If you prefer to avoid the import, you could pretty easily write your own generator to do this sort of thing as well:

def counter(val=0):
    while True:
        yield val
        val += 1
like image 108
mgilson Avatar answered Apr 06 '23 17:04

mgilson