Given a list = ["one", "two", "three"] I would like to print current and its next element, but in reverse order. That is:
three one
two three
one two
my script prints current and next element, but not in reverse order:
# It prints:
# one two
# two three
for curr, nxt in zip(list, list[1:]):
print(curr, nxt)
- How can I edit my script so that I achieve my goal?
I tried the following:
# It prints:
# three one
for curr, nxt in zip(list[-1:], list):
print(curr, nxt)
but it only gives me one result.
>Solution :
Python’s zip is not the solution I would go for here, as you would need to concatenate two arrays in order to get the circularly shifted array (slice alone cannot shift circularly). What I would do however is simply run over all of the elements in the reversed list, and get the next value by it’s index, like so:
list = ["one", "two", "three"]
for i, curr in enumerate(list[::-1]): # enumerate gives you a generator of (index, value)
nxt = list[-i] # list[-i-1] would be the current value, so -i would be the next one
print(curr, nxt)
Edit:
Using list[::-1] is slightly slower than you would normally want it, because it would go over the list once to reverse it, and then another time to iterate over it. A better solution would be:
list = ["one", "two", "three"]
for i in range(len(list)-1, -1, -1):
curr = list[i]
nxt = list[len(list) - i - 1] # list[i+1] would not work as it would be index out of range, but this way it overflows to the negative side, which python allows.
print(curr, nxt)
If you do however wish to use zip, you would need to do this:
list = ["one", "two", "three"]
for curr, nxt in zip(list[::-1], [list[0]] + list[:0:-1]):
print(curr, nxt)
You should also note that naming your variable list is not a good idea as you would then shadow python’s built in list method, you should probably name it lst or something similar to that.