0

I have a sample list of strings:

my_list = ['hello','this','is','a','sample','list', 'thanks', 'for', 'help']

And I want to club every three elements together, like:

new_list = ['hello this is', 'a sample list', 'thanks for help']
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

4 Answers4

4

Just split into chunks and join:

[' '.join(my_list[i:i+3]) for i in range(0, len(my_list), 3)]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0

Option 1: This solution drop elements if my_list length is not divisible by 3

input string: ['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']

[" ".join(i) for i in zip(*[iter(my_list)]*3)]

result: ['hello this is', 'a sample list', 'thanks for help']

how python iter trick works: How does zip(*[iter(s)]*n) work in Python?

Option 2: keep extra element with zip_longest

input string: ['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']

[" ".join(i) for i in zip_longest(*[iter(my_list)]*3, fillvalue='')]

result: ['hello this is', 'a sample list', 'thanks for help', 'foo ']

Erwan
  • 587
  • 4
  • 23
  • 1
    Note, this approach will leave off anything at the end if the length of the list isn't divisible by 3. This may or may not be a problem, but it is probably worth noting – juanpa.arrivillaga Aug 17 '18 at 06:13
0

You can solve this by iterating using a step, in this case 3 steps, and adding the individual strings under each step, i.e., my_list[i], my_list[i+1]. my_list[i+2 ]. Note that you need to add a space after each first and second string. This piece of code does that:

new_list = []
for i in range(0, len(my_list), 3):
    if i + 2 < len(my_list):
        new_list.append(my_list[i] + ' ' + my_list[i+1] + ' ' + my_list[i+2])
print(new_list)

The output is as expected:

['hello this is', 'a sample list', 'thanks for help']
Jay272600
  • 168
  • 1
  • 8
0

A couple of solutions using itertools are possible.

Using groupby:

[' '.join(x[1] for x in g) for _, g in groupby(enumerate(my_list), lambda x: x[0] // 3)]

Using tee and zip_longest:

a, b = tee(my_list)
next(b)
b, c = tee(b)
next(c)
[' '.join(items) for items in zip_longest(a, b, c, fillvalue='')]

Using just zip_longest:

[' '.join(g) for g in zip_longest(*[iter(my_list)] * 3, fillvalue='')]

The last two are adapted from the pairwise and grouper recipes in the documentation. Only the first option won't add extra spaces at the end of your last group if the aren't a multiple of 3 words.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264