CapnShanty CapnShanty - 3 years ago 315
Python Question

How to combine lists of different lengths repeating elements?

so I have say two lists:

list1 = [1,2,3]


list2 = [4]

and I need to combine them to produce the following output:


doesn't seem to have a method to accomplish this, the
function ends when the second list does...

I'm sure there's a one liner out there, but I'm finding too much stuff about similar but not the same problems on here and google.

Thanks for any help!

Answer Source

You can iterate over the list and concatenate the list2 value and the element for the current iteration:

list1 = [1,2,3]
list2 = [4]
new_list = [[a]+list2 for a in list1]


[[1, 4], [2, 4], [3, 4]]

Or, an alternative, although lower solution using map:

final_list = map(lambda x:[x, list2[0]], list1)


[[1, 4], [2, 4], [3, 4]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download