Iterate consecutive elements in a list in Python such that the last element combines with first

  • A+
Category:Languages

I have a list:

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

I want to iterate consecutive elements in the list such that, when it comes to last element i'e 8 it pairs with the first element 1.

The final output I want is:

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

I tried using this way:

for first,second in zip(L, L[1:]):     print([first,second]) 

But I am getting only this result:

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

How do I make a pair of last element with first? I have heard about the negative indexing property of a list.

 


You can simply extend the second list in zip() with a list with only the first item, something like:

for first, second in zip(L, L[1:] + L[0:1]):  # or simply zip(L, L[1:] + L[:1])     print([first, second]) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: