0

I have this piece of python code

xy_tups = []
for x in ['m', 't', 'b']:
    for y in ['b', 't', 'e']:
        if x != y:
            xy_tups.append ((x, y))

that outputs this: [('m', 'b'), ('m', 't'), ('m', 'e'), ('t', 'b'), ('t', 'e'), ('b', 't'), ('b', 'e')]

I need to create a list comprehension version of this piece of code but I am having trouble figuring it out. I have tried these methods

 xy_tups = [x for x in ['m', 't', 'b'] and y for y in ['b', 't', 'e'] if x != y] 

 xy_tups = [x for y in ['m', 't', 'b'] and y for x in ['b', 't', 'e'] if x != y]

and I have tried adding the xy_tups.append(x,y) to the list comprehension code but I get errors. I understand that each letter in the x list is joined with each letter of the y list once, but I cannot figure out how to put together the list comprehension.

jdaz
  • 5,964
  • 2
  • 22
  • 34
Chey
  • 35
  • 4
  • 3
    The [docs](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) have an example, nearly exactly like your question. – Michael Butscher Mar 21 '19 at 01:27
  • Here's an alternate approach of you're not limited to using list comprehension. https://stackoverflow.com/questions/46918272/combinations-of-2-lists – Nidal Mar 21 '19 at 01:32

2 Answers2

1
xy_tups = [(x,y) for x in ['m , 't', 'b'] for y in ['b', 't', 'e'] if x != y ]
print(xy_tups)

Output: [('m', 'b'), ('m', 't'), ('m', 'e'), ('t', 'b'), ('t', 'e'), ('b', 't'), ('b', 'e')]

Sonu Sharma
  • 304
  • 4
  • 13
0
[(a, b) for a in ['m', 't', 'b'] for b in ['b', 't', 'e'] if a != b]

outputs

[('m', 'b'), ('m', 't'), ('m', 'e'), ('t', 'b'), ('t', 'e'), ('b', 't'), ('b','e')]
nj1234
  • 66
  • 4