1

I am a newbie in python, I have two lists:

l1 = ['a','b','c','d']
l2 = ['new']

i want to get new list like this

l3 = [('a','new'),('b','new'),('c','new'),('d','new')]

What is the best way to combine the two lists?

Mat
  • 202,337
  • 40
  • 393
  • 406
kuslahne
  • 720
  • 4
  • 10
  • 21

5 Answers5

5
>>> from itertools import product
>>> l1 = ['a','b','c','d']
>>> l2 = ['new']
>>> list(product(l1,l2))
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')]
jamylak
  • 128,818
  • 30
  • 231
  • 230
5

If l2 always just has the one element there is no need to overcomplicate things

l3 = [(x, l2[0]) for x in l1]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
3

See the itertools docs.

In particular, use product for a Cartesian product:

from itertools import product:
l1 = ['a','b','c','d']
l2 = ['new']
# Cast to list for l3 to be a list since product returns a generator
l3 = list(product(l1, l2))  
bossylobster
  • 9,993
  • 1
  • 42
  • 61
2
>>> from itertools import repeat
>>> l1 = ['a','b','c','d']
>>> l2 = ['new']
>>> zip(l1,repeat(*l2))
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')]
jamylak
  • 128,818
  • 30
  • 231
  • 230
0

You can simply take use of list comprehension without any functions:

l3 = [(x, y) for x in l1 for y in l2]

Hui Zheng
  • 10,084
  • 2
  • 35
  • 40