-1

So I have two list

A = ['astr1', 'astr2', 'astr3']

and

B = ['bstr11','bstr12']

now I want a final list which sould be a combination of two and will look like this,

C = [['astr1', 'bstr11','bstr12'], ['astr2', 'bstr11','bstr12'], ['astr3', 'bstr11','bstr12']]

I tried extending list A using for loop over B but since it happens on single elements as strings, extend doesn't work. any leads ?

EDIT:

for i in range(len(A)):
    A[i].extend(B)
  • 2
    You should include what you've tried – Sayse Aug 07 '18 at 08:28
  • 1
    Iterating over a mutable list, which is modified within the loop is always a bad idea. – guidot Aug 07 '18 at 08:30
  • I don't understand the downvotes here, it's a legit question. – Mehar Charan Sahai Aug 07 '18 at 08:32
  • Possible duplicate of [Quick way to “multiply” every element in a list with another list in Python](https://stackoverflow.com/questions/30195170/quick-way-to-multiply-every-element-in-a-list-with-another-list-in-python) – jpp Aug 07 '18 at 08:35

1 Answers1

0

You can use a list comprehension for this:

In [1]: a = [1,2,3]
In [2]: b = [11,12]
In [3]: c = [[e] + b for e in a]
In [4]: c
Out[4]: [[1, 11, 12], [2, 11, 12], [3, 11, 12]]
Joe
  • 12,057
  • 5
  • 39
  • 55
Bernd
  • 112
  • 7
  • what's the diff between `[list(e) + b for e in a]` and `[[e] + b for e in a]` – Mehar Charan Sahai Aug 07 '18 at 08:38
  • 2
    @MeharCharanSahai try it? If you pass an argument to `list()` it expects an iterable that it can convert into a list. e.g. `list('hello')` will become a list of individual characters. `[]` does not do this. – roganjosh Aug 07 '18 at 08:51
  • 1
    Mehar - `list(e)` will fail. Try it... try `list(3)`. `list` takes an iterable as a param. – Potrebic Aug 07 '18 at 09:15