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']
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']
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.
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)
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])]
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 ;-)