0

I am new to python

I have list_a as ['A','B'] and list_b as ['C','D']

output I have to get is in this format [['AC','BC'],['AD','BD']]

When I tried with this below code:

output = []

for a in ['A','B']:

    for b in ['C','D']:
        if a !=b:
            output.append([a,b])
print output

I Got output as [['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D']]

I am not sure what I am doing wrong.

2 Answers 2

2

Define lists a and b:

>>> a = ['A','B'];  b = ['C','D']

Now, combine them:

>>> [ [x + y for x in a] for y in b ]
[['AC', 'BC'], ['AD', 'BD']]

Explicit Looping

If you really must do explicit loops:

outer = []
for y in ['C','D']:
    inner = []
    for x in ['A','B']:
        inner.append(x + y)
    outer.append(inner)
print(outer)

This results in:

[['AC', 'BC'], ['AD', 'BD']]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your valuable explanation John
0

Mostly, you're looping in the wrong order...

output = []
for b in list_b:
    output.append([a + b for a in list_a])

gives you [['AC', 'BC'], ['AD', 'BD']] as desired.

1 Comment

@Bhanu, great! So please accept either John's sophisticated answer or my simpler one so the question is seen as resolved.

Your Answer

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