Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehensions in python

Tags:

python

list

Is there any way I can combine two list a and b into c using list comprehensions in python,

a=[1,2,3]
b=['a','b']

c=['1a','1b','2a','2b','3a','3b'] 
like image 530
Sudhagar Sachin Avatar asked Nov 17 '25 20:11

Sudhagar Sachin


2 Answers

>>> a = [1,2,3]
>>> b = ['a', 'b']
>>> c = ['%d%c' % (x, y) for x in a for y in b]
>>> c
['1a', '1b', '2a', '2b', '3a', '3b']
like image 58
Maehler Avatar answered Nov 19 '25 10:11

Maehler


>>> from itertools import product
>>> a=[1,2,3]
>>> b=['a','b']
>>> ['%d%s' % el for el in product(a,b)]
['1a', '1b', '2a', '2b', '3a', '3b']

With new string formatting

>>> ['{0}{1}'.format(*el) for el in product(a,b)]
['1a', '1b', '2a', '2b', '3a', '3b']
like image 21
jamylak Avatar answered Nov 19 '25 09:11

jamylak