0

How to compress this whole loop into one single line. Is there any way?

aa = []  
for x in args:
   for y in args:
     if x == y:
       pass
     else:
       kk = x*y
       aa.append(kk)

zircon
  • 742
  • 1
  • 10
  • 22
  • Does this answer your question? [Nested For Loops Using List Comprehension](https://stackoverflow.com/questions/3633140/nested-for-loops-using-list-comprehension) – mkrieger1 Sep 14 '20 at 23:03
  • Does this answer your question? [Find cartesian product of lists filtering out the elements based on condition](https://stackoverflow.com/questions/48791751/find-cartesian-product-of-lists-filtering-out-the-elements-based-on-condition) – Gino Mempin Sep 15 '20 at 00:46
  • Nested Loops are easy but conditions with it making it difficult@mkrieger1, @Gino Mempin – zircon Sep 15 '20 at 08:21

2 Answers2

1
from itertools import product
aa = [x*y for x,y in product(args, args) if x != y]
1

Absolutely nothing wrong with previous answer. A double loop also works and might be a little simpler to understand.

[x * y for x in args for y in args if x != y]
Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
  • ``` total = 0 for x in args: total = total + x total2= 2*total ``` can this be compred in one line @Frank Yellin – zircon Sep 15 '20 at 08:31