How to combine two lists to get the following desired result containing tuples?

61 Views Asked by At

I have two lists as:

a = ['apple', 'mango', 'pear']

b = ['ripe','raw','rotten']

How can I get the following result list of tuples as:

[(('apple', 'mango', 'pear'), 'ripe'), (('apple', 'mango', 'pear'), 'raw'), (('apple', 'mango', 'pear'), 'rotten')]
5

There are 5 best solutions below

0
On BEST ANSWER

list(itertools.product(a,b)) will use the element in the A.To make the full list as a element, you could use nested list,like:

list(itertools.product([tuple(a)], b)

Result:

[(('apple', 'mango', 'pear'), 'ripe'), (('apple', 'mango', 'pear'), 'raw'), (('apple', 'mango', 'pear'), 'rotten')]
1
On

Have you tried to solve by yourself?

Try this :-

c = []
for i in b:
    c.append((tuple(a), i)) 
print (c) 
1
On

The usual method is to use a list comprehension:

>>> [(tuple(a), x) for x in b]
[(('apple', 'mango', 'pear'), 'ripe'), (('apple', 'mango', 'pear'), 'raw'), (('apple', 'mango', 'pear'), 'rotten')]

If they don't have to be tuples, you can also use zip:

>>> list(zip([a]*len(b), b))
[(['apple', 'mango', 'pear'], 'ripe'), (['apple', 'mango', 'pear'], 'raw'), (['apple', 'mango', 'pear'], 'rotten')]
1
On

Try this in just one line:

[(tuple(a), i) for i in b]

output will be:

[(('apple', 'mango', 'pear'), 'ripe'),
 (('apple', 'mango', 'pear'), 'raw'),
 (('apple', 'mango', 'pear'), 'rotten')]
0
On

You can try this:

a = ['apple', 'mango', 'pear']

b = ['ripe','raw','rotten']

list=[ ]
for i in b:
    k=((tuple((tuple(a),i))))
    list.append(k)

print(list)