CapnShanty
CapnShanty

Reputation: 559

How to zip two lists where one list contains just one item

I have two lists:

list1 = [1,2,3]

and

list2 = [4]

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

list3 = [[1,4],[2,4],[3,4]]

itertools doesn't seem to have a method to accomplish this, the zip 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.

Upvotes: 3

Views: 546

Answers (5)

Aaditya Ura
Aaditya Ura

Reputation: 12669

Are you looking for something like this?

Without any external module or heavy code:

print(list(map(lambda x:[x,list2[0]],list1)))

when data is :

list1 = [1,2,3]
list2 = [4]

output:

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

As someone pointed out this is already given answer ,Here is another solution:

list1 = [1,2,3]
list2 = [4]

print(list(zip(list1,list2*len(list1))))

output:

[(1, 4), (2, 4), (3, 4)]

Upvotes: -1

RoadRunner
RoadRunner

Reputation: 26315

You can also try using itertools.cycle():

>>> import itertools    
>>> list1 = [1,2,3]
>>> list2 = [4]
>>> print([list(x) for x in zip(list1, itertools.cycle(list2))])
[[1, 4], [2, 4], [3, 4]]

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71451

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]

Output:

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

Or, an alternative, although lower solution using map:

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

Output:

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

Upvotes: 6

Anton vBR
Anton vBR

Reputation: 18906

You can use itertools izip_longest (py2) or itertools zip longest (py3) too:

import itertools

list(map(list,itertools.izip_longest([], list1, fillvalue=list2[0])))

Returns:

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

Upvotes: 6

Bill Bell
Bill Bell

Reputation: 21643

Do you need a third alternative?

>>> list(map(list,zip(list2 * len(list1), list1)))
[[4, 1], [4, 2], [4, 3]]

Upvotes: 3

Related Questions