user001
user001

Reputation: 515

Get the element of list or index of list while "for" looping with step in range

I am looping through a list with step as below:

list_of_names = ["james", "jack", "jill"]

for i in range(1, len(list_of_names) * 6 + 1, 7):
    print(i, i + 6)

Now I want to get the index of the element or the iteration number so that i can print the current element of the list. So I want the output to be

(1, 7, "james")
(8, 14, "jack")
(15, 21, "jill")

or

(1, 7, 0)
(8, 14, 1)
(15, 21, 2)

How can I do that?

Note: I am using python2.

Upvotes: 0

Views: 505

Answers (1)

frippe
frippe

Reputation: 1390

The logic isn't identical to your version, but maybe you want to achieve something similar to this?

for i, name in enumerate(list_of_names):
    print(i * 7 + 1, (i + 1) * 7, name)

In your version, as list_of_names grows, the number of elements that aren't printed will increase by one at each list length n*6 + 1, n being a positive integer. For instance, when the length is 7, only the first 6 items will be printed (i.e., i taking on values [1, 8, 15, 22, 29, 36], but not 43) and by length 13, only 11 elements would be printed.

If possible, you should be using Python 3 instead. Python 2 is no longer maintained.

Upvotes: 1

Related Questions