Home > Mobile >  How to iterate a list accessing two indexes at a time and moving one index time after each iteration
How to iterate a list accessing two indexes at a time and moving one index time after each iteration

Time:10-01

if I have a list like this:

a_list = [1,2,3,4,5,6,7,8]

how would I iterate it to produce this output:

1,2
2,3
3,4
4,5
5,6

and so on?

Thank you

CodePudding user response:

You could use a zip with an offset on the start and stop:

print(list(zip(a_list[:-1], a_list[1:])))

Slightly more flexible solution that doesn't rely on list syntax.

def special_read(data):
    last = None
    for curr in data:
        if last is not None:
            yield last, curr
        last = curr

...

for a, b in special_read(a_list):
    print(a, b)

CodePudding user response:

Another solution (it will handle uneven lists):

a_list = [1, 2, 3, 4, 5, 6, 7, 8]

for i in range(0, len(a_list), 2):
    print(a_list[i], "" if i   1 == len(a_list) else a_list[i   1], sep=",")

Prints:

1,2
3,4
5,6
7,8

For a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] it will print:

1,2
3,4
5,6
7,8
9,

CodePudding user response:

After reviewing I made a similar attempt at this problem:

a_list = [1,2,3,4,5,6,7,8]
a_count = 0

for i in a_list:
    if a_count == len(a_list) - 1:
        break
    else:
        print(a_list[a_count],',', a_list[a_count 1]) 
        a_count =1
  • Related