Search code examples
python-3.xlistcollectionstuplespython-itertools

Generate list of i & i+1 combinations


I have the following list:

i = [1,2,3,4,5,6]

I would like to turn this list into a list of i & i+1 combinations (I'm not sure if this is clear). For example, I'd like it to look like this:

>>> [[1,2],[2,3],[3,4],[4,5],[5,6]]

So far I've tried this:

temp = []
sequence = []
x = [1,2,3,4,5,6]

for i, val in enumerate(x):

    temp.append(val)

    if i != 0 and i%2!=0:
        sequence.append(temp)
        temp = []

but it returns this:

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

What am I doing wrong? Is there a function is the collections or itertools library that does this? Thanks in advance!


Solution

  • Ok, so your main issue (minus variable names being mixed up) is that your only appending to sequences every other value which is why its skipping [2,3] and [4,5] (basically anywhere that starts with an even number). Your other issue is that your not adding the even number values back into temp after clearing it. This causes an issue with your if statement in that its not actually appending as often as it needs to.

    temp = []
    sequences = []
    x = [1,2,3,4,5,6]
    
    for i, val in enumerate(x):
    
        temp.append(val)
    
        if i != 0:
            sequences.append(temp)
            temp = []
            temp.append(val)