Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 796
Shubham R Avatar asked Aug 22 '18 12:08

Shubham R


People also ask

How do you repeat the last item in a list Python?

We can use the append() method, the extend() method, or the * operator to repeat elements of a list in python.

How do you find consecutive elements in a list?

We have to check whether it contains contiguous values or not. So, if the input is like nums = [6, 8, 3, 5, 4, 7], then the output will be true as the elements are 3, 4, 5, 6, 7, 8. otherwise, j := nums[i] - min_val.

What is pair () in Python?

To enable us to implement the concrete level of our data abstraction, Python provides a compound structure called a tuple, which can be constructed by separating values by commas. Although not strictly required, parentheses almost always surround tuples.

How do you make an ordered pair in Python?

Practical Data Science using Python Follow the below steps to solve the problem. Initialize the lists with elements. Iterate over the lists and append the pair into a list if the corresponding elements from the lists are not same. Print the result.


3 Answers

You can just append the front element(s) to the back.

for first,second in zip(L, L[1:] + L[:1]):
    print([first,second])
like image 51
Ben Jones Avatar answered Oct 25 '22 13:10

Ben Jones


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])
like image 36
Kamil Avatar answered Oct 25 '22 14:10

Kamil


You can use cycle to cycle the lists (in combination with islice to skip the first element):

from itertools import cycle, islice

L = [1,2,3,4,5,6,7,8]
rest_L_cycled = islice(cycle(L), 1, None)
items = zip(L, rest_L_cycled)
print(list(items))

This is easily extensible. Note that it relies on the fact that zip halts on the shorter list (the second argument is an infinite cycle). It also does everything lazily and does not create any intermediate list (well, except for the printed list) :-)

like image 44
Reut Sharabani Avatar answered Oct 25 '22 12:10

Reut Sharabani