pythonlist

how to pair each 2 elements of a list?


I have a list like this

attach=['a','b','c','d','e','f','g','k']

I wanna pair each two elements that followed by each other:

lis2 = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'k')]

I did the following:

Category=[] 
for i in range(len(attach)):
    if i+1< len(attach):
        Category.append(f'{attach[i]},{attach[i+1]}')

but then I have to remove half of rows because it also give 'b' ,'c' and so on. I thought maybe there is a better way


Solution

  • You have to increment iterator i.e by i by 2 when moving forward

    Category=[] 
    for i in range(0, len(attach), 2):
        Category.append(f'{attach[i]},{attach[i+1]}')
    

    Also, you don't need the if condition, if the len(list) is always even