Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating over 2 elements in a list but repeating the second element in the next iteration

How do I make a for loop or a list comprehension so that every iteration gives me two elements but the last value must be repeated.

l = [1,2,3,4,5,6]

for i,k in ???:
    print str(i), '+', str(k), '=', str(i+k)

Output:

1+2=3
2+3=5
3+4=7
4+5=9
...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use zip:

l = [1,2,3,4,5,6]
for i,k in zip(l, l[1:]):
    print(f'{i} + {k} = {i+k}')

Output:

1 + 2 = 3
2 + 3 = 5
3 + 4 = 7
4 + 5 = 9
5 + 6 = 11

For more explanation:

>>> list(zip(l, l[1:]))
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading