4

Given the following lists:

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

I'd like to produce this:

c = ['a1','a2','a3','a4','b1','b2','b3','b4']

So I basically want to join every element of b to each element in a.

I'd like an approach similar to this:

[x+str(y) for x in a and y in b]

Thanks in advance!

1
  • c = [x+str(y) for x in a and y in b] is the solution which you have included in your question, what are you actually asking for? Commented Dec 16, 2016 at 20:16

6 Answers 6

5
a = ['a','b']
b = [1,2,3,4]
c = [x+str(y) for x in a for y in b]
print(c)
Sign up to request clarification or add additional context in comments.

2 Comments

+0.5 for your answer, and +0.5 for your username.
ditto, @elethan's comment :P
3

You need to iterate twice within the list comprehension as:

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

>>> [i+str(j) for i in a for j in b]
['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4']

2 Comments

Haha, looks like you are the winner ;)
@HillaryClintonEmailRemover BTW I liked your name :D :D
2

You can also mix list comprehension with generation of combinations. Itertools module is a good way how to work with combinations.

import itertools
c = [x + str(y) for x, y in itertools.product(a, b)]

Comments

1

Try this, replacing the and in your example with a for to add an extra loop:

[x + str(y) for x in a for y in b]

This will loop through both lists in a single list comprehension.

Comments

0
[str(a1) + str(b1) for a1 in a for b1 in b]

Comments

0

I arrived too late to this question, but here are my two cents for doing this on python 3.6+

[f'{a_item}{b_item}' for a_item in a for b_item in b]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.