1

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

fuenfundachtzig
  • 7,952
  • 13
  • 62
  • 87

3 Answers3

2

You can use zip() to achieve this as:

my_list = ['a','b','c','d','e','f','g','k']
new_list = list(zip(my_list[::2], my_list[1::2]))

where new_list will hold:

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

This will work to get only the pairs, i.e. if number of the elements in the list are odd, you'll loose the last element which is not as part of any pair.

If you want to preserve the last odd element from list as single element tuple in the final list, then you can use itertools.zip_longest() (in Python 3.x, or itertools.izip_longest() in Python 2.x) with list comprehension as:

from itertools import zip_longest # In Python 3.x
# from itertools import izip_longest ## In Python 2.x

my_list = ['a','b','c','d','e','f','g','h', 'k']
new_list = [(i, j) if j is not None else (i,) for i, j in zip_longest(my_list[::2], my_list[1::2])]

where new_list will hold:

[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h'), ('k',)]
#   last odd number as single element in the tuple ^ 
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

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

1
lis2 = [(lis[i],lis[i+1]) for i in range(0,len(lis),2)]
lis2

You can use list comprehension

Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25