-6

I need to do the following using list comprehension

ans = []
for i in range(0, x):
    l = []
    for j in range(0, y):
        l.append(i*j)
    ans.append(l)
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Vinay
  • 17
  • 1
  • 8
  • 4
    What did you try, and how was it deficient? – Scott Hunter Aug 27 '19 at 17:48
  • I tried the following things:` ans = [i*j for i in range(0,x) l = [] for j in range(0,y)] ans = [ans[i:i+y] for i in range(0, len(ans), y)] ` – Vinay Aug 27 '19 at 17:54
  • Your code seems ok, too. How does it not work? – justhalf Aug 27 '19 at 17:56
  • you should search for your question on SO. if you didnt find a match then you can ask the Question. – basilisk Aug 27 '19 at 18:00
  • @justhalf It worked but I couldn't figure out how to do it using list comprehension – Vinay Aug 27 '19 at 18:00
  • @basilisk Yeah i tried but didn't get any significant answer so I asked.. Again, will note this point – Vinay Aug 27 '19 at 18:02
  • 1
    @Vinay Sorry but I don't think you made a good search because this link https://stackoverflow.com/questions/3633140/nested-for-loops-using-list-comprehension explain clearly what you want to do and how the answer should be. The Community can help you reach your answer but it would be very bad for you if the Community will do your homework. in this way you ll learn nothing. I'm trying to help you here. I promise it would be better if you tried to learn on yourself it will pay back in the future. very soon ;) – basilisk Aug 27 '19 at 18:06

2 Answers2

-1

Here's a list comprehension that is equivalent to your nested loops:

a = [[i * j for j in range(0, y)] for i in range(0, x)]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
-1

Since you want individual list:

ans = [[i*j for j in range(y)] for i in range(x)]

If you want it flattened:

ans = [i*j for i in range(x) for j in range(y)]
justhalf
  • 8,960
  • 3
  • 47
  • 74