mgri
mgri

Reputation: 267

Increasing the counter in a list every two elements

I have a list of elements:

list = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5']

which I use in pairs in this way:

for x in range(0, len(list)-1):
    print(list[x], list[x+1])

This works and returns:

('elem1', 'elem2')
('elem2', 'elem3')
('elem3', 'elem4')
('elem4', 'elem5')

I would like to increase a counter every time I print a row. How can I do this?

Upvotes: 0

Views: 1593

Answers (3)

omri_saadon
omri_saadon

Reputation: 10631

First of all don't use list as a variable name, that can cause some serious problems.

Second, the simple way is just initial a counter and increment it inside the loop.

li = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5']

cnt = 0
for index in range(0, len(li)-1):
    cnt += 1
    print(li[index], li[index+1])

print cnt

Another elegant way to create the required output is:

li = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5']

for cnt, (v, w) in enumerate(zip(li[:-1], li[1:])):
    print [v, w]

print cnt

Here we separate it into two lists, the first one is ['elem1', 'elem2', 'elem3', 'elem4'], the second is ['elem2', 'elem3', 'elem4', 'elem5'].

Each iteration we take one from the first list and the second from the second list.

Upvotes: 3

ycesar
ycesar

Reputation: 440

You can declare a variable with the initial value you want before the for loop and increase it inside the for:

    counter = 0
    for x in range(0, len(list)-1):
        print(list[x], list[x+1])
        counter += 1

Upvotes: 1

nbryans
nbryans

Reputation: 1527

This solution declares a variable called count and increases it every iteration

listX = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5']
count = 0
for x in range(0, len(listX)-1):
    print(list[x], list[x+1])
    count += 1

Upvotes: 1

Related Questions