Combine two lists in equal amounts

The problem is combining the two lists while maintaining order and in the same number of elements in the combined list, which cannot contain more than 10 (or any numbers) of elements, but as much as possible.

This is the simplest example.

l1 = list('1'*10)
l2 = list('2'*10)
lt = l1[:5] + l2[:5]

However, if there are no 5 items in one list, the new list is populated with items from another list.

l1 = list('1'*2)
l2 = list('2'*10)
lt = ['1','1','2','2','2','2','2','2','2','2']

l1 = list('1'*10)
l2 = list('2'*2)
lt = ['1','1','1','1','1','1','1','1','2','2']

The function must accept lists with any number of elements. It should be simple, but it is not.

+3
source share
1 answer

Do you want to take what is ever greater: five elements from the list or enough elements to fill the list to the desired length.

lt = l1[:max(5, 10 - len(l2))] + l2[:max(5, 10 - len(l1))]
+5
source

All Articles