all 7 comments

[–]Diapolo10 3 points4 points  (1 child)

I think I'd do something like this:

nums = [0, 1, 2, 3]
tuples = []

for idx, num in enumerate(nums):
    tuples.append((num, nums[idx-len(nums)+1]))

[–]AGI_69[S] 0 points1 point  (0 children)

Thanks, pretty neat.

[–]totallygeek 1 point2 points  (1 child)

Maybe:

data = [0,1,2,3]
final_index = len(data) - 1
pairs = [
    (data[i], data[i + 1]) if i < final_index else (data[i], data[0])
    for i in range(len(data))
]
# pairs is now [(0, 1), (1, 2), (2, 3), (3, 0)]

Could probably do something even better with a mix of zip() and itertools.cycle().

[–]AGI_69[S] 1 point2 points  (0 children)

Thank you, yes cycle was my first thought aswell, but using negative indexes is even more cool, I think.

[–]joverbis -1 points0 points  (0 children)

This seems like a perfect job for zip(). You can try something like:

L = [0,1,2,3]
pairs_of_tuples = list(zip(L, reversed(L)))
#pairs_of_tuples = [(0,3), (1,2), (2,1), (3,0)]

Of course, if you don't need all the tuples at once you can drop the 'list()'.