2

I have a list in python and i would like to merge every second element of it. So turn this:

['apple', 'red', 'banana', 'yellow', 'blueberry', 'blue']

into this:

['apple red', 'banana yellow', 'blueberry blue']

4 Answers4

2

Here's a simple solution assuming your data is a variable called l:

from itertools import zip_longest
[' '.join(filter(None, pair)) for pair in zip_longest(l[::2], l[1::2])]

Using zip_longest ensures that odd numbers of values will have the last element included.

Edit: Added a filter on None to make sure the odd element does not have a space appended to it.

ApplePie
  • 8,814
  • 5
  • 39
  • 60
1
list = ['apple', 'red', 'banana', 'yellow', 'blueberry', 'blue']
newList = []
x = 0

for i in range (len(list)):
    x += 1
    if x % 2 == 0:
        newList.append(f"{list[i-1]} {list[i]}")

print(newList)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Tkinter Lover
  • 835
  • 3
  • 19
  • I would advise against using `list` as a variable name as it is a built-in keyword. Instead of using f-string you can use the more pythonic `" ".join(list[i-1], list[i])`. – ApplePie Mar 15 '21 at 23:44
1

Just use a simple list comprehension. For this split the original list into two lists - one starts with the 0-th element and goes through every second element and the second list starts with the first element and similarly iterates over every second element:

i = ['apple', 'red', 'banana', 'yellow', 'blueberry', 'blue']
b = [f'{a} {j}' for a, j in zip(i[::2], i[1::2])]
NotAName
  • 3,821
  • 2
  • 29
  • 44
  • 1
    This will ignore the last element in an odd-length list because of the call to zip instead of zip_longest. – ApplePie Mar 15 '21 at 23:53
  • @ApplePie, agree, but then the question was about combining in pairs so if there's no pair it would make sense to omit it. – NotAName Mar 16 '21 at 00:24
0

You could also do this:

l = ['apple', 'red', 'banana', 'yellow', 'blueberry', 'blue']
l1 = iter(l)
l2 = iter(l)
next(l2, None)
res = []
for _ in zip(l1, l2):
  next(l1, None)
  res.append(' '.join(_))
  next(l2, None)
  
print(res)

Just for the fun of using iter and next ;-)

DevLounge
  • 8,313
  • 3
  • 31
  • 44