How to merge every three (or more) elements of list in one in python?

Question:

list = [1, 'one', 'first', 2, 'two', 'second', 3, 'three', 'third', 4, 'four', 'fourth', 5, 'five', 'fifth', 6, 'six', 'sixth']

is it compact way to make new list like this? (merging 3 elements, then another 3…):

['1onefirst', '2twosecond', '3threethird', '4fourfourth', '5fivefifth', '6sixsixth']

Answers:

I hope the following solution is what you are looking for.

    list = [1, "one", "first", 2, "two", "second", 3, "three", "third",
    4, "four", "fourth", 5, "five", "fifth", 6, "six", "sixth"]

    def merge_list(list, n):
        temp_list = [list[i:i + n] for i in range(0, len(list), n)]
        return [''. join(str(i) for i in temp_list) for temp_list in temp_list]

   list_merge_every_third = merge_list(list, 3)
   print(list_merge_every_third)

The resulting list looks like this:

[‘1onefirst’, ‘2twosecond’, ‘3threethird’, ‘4fourfourth’, ‘5fivefifth’, ‘6sixsixth’]

Answered By: Markus Schmidgall

You may want to use a combination of list comprehensions and slices for this purpose in Python:

# Defining the input list
input_list = [
    1, "one", "first",
    2, "two", "second",
    3, "three", "third",
    4, "four", "fourth",
    5, "five", "fifth",
    6, "six", "sixth"
]

# Using slices of the input in a list comprehension
list_merge_every_third = [
    ''.join(str(e) for e in input_list[i * 3 : i * 3 + 3])
    for i in range(len(input_list) // 3)
]

Note: You may first want to test if your input list length is a multiple of 3.

I also suggest not using the symbol "list" to designate your input, because it is a reserved keyword of the Python language to designate the list type.

Answered By: Nicolas Misk

Using a list comprehension with conversion to string and join:

N = 3
out = [''.join(map(str, lst[i:i+N])) for i in range(0, len(lst), N)]

Output:

['1onefirst',
 '2twosecond',
 '3threethird',
 '4fourfourth',
 '5fivefifth',
 '6sixsixth']
Answered By: mozway
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.