Is there a way of doing this?

Viewed 65

The problem is this:

groups=[1,2,3..etc] # all the way up to 16 numbers (random numbers)

for i in groups:
    if groups.index(i)% 2 != 0:
        value=groups[groups.index(i)]-groups[groups.index(i)-1]
        print(value)

Using that code, I should get 8 numbers, but the number fluctuates. Can anyone help me find a solution or tell me what's wrong?

1 Answers

Because you have random sequence of numbers, sometimes it contains duplicates, and groups.index(i) returns the index of first occurrence. More pythonic way is:

for i, n in enumerate(groups):
    if i % 2 != 0:
        print(n)

enumerate is a good way to generate (position , value) tuples from the list

Related