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.
We can use the append() method, the extend() method, or the * operator to repeat elements of a list in python.
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.
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.
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.
You can just append the front element(s) to the back.
for first,second in zip(L, L[1:] + L[:1]):
print([first,second])
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])
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 print
ed list) :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With