-1

Can someone explain to me step by step to understand how to arrive at the result of this loop?

>>> [ (a, b) for a in range(3) for b in range(a) ]
[(1, 0), (2, 0), (2, 1)]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
X coder
  • 65
  • 6
  • Sorry for misreading my question being new to StackOverFlow. Thanks to @jonrsharpe for editing this. However, making me diminish my reputation is not cool. Explaining myself would have been more profitable. – X coder Nov 28 '21 at 13:05
  • Please stop unformatting the code. If you don't want to get downvotes, there's lots of guidance at e.g. [ask]. – jonrsharpe Nov 28 '21 at 13:08
  • Ok. I had a display error and barely discovering StackOverFlow. Thanks for your advice. – X coder Nov 28 '21 at 13:13

1 Answers1

3

It's equivalent to this:

rtrn = []
for a in range(3):
    for b in range(a):
        rtrn.append((a, b))

Note how the first iteration of the outer loop does not produce any output because the inner loop is then range(0) which does zero iterations.

Homer512
  • 9,144
  • 2
  • 8
  • 25
  • Thank you for your response and your responsiveness, I will try to think about it but I admit that I have not yet fully understood. – X coder Nov 28 '21 at 12:46
  • @Xcoder It often helps to put print statements in various places to see the order of operations. Also don't feel too bad about it. Even as a seasoned Python programmer I find the double loop in list comprehensions confusing and I try to avoid it. Oh, and if you are satisfied with my answer, please mark it as correct. – Homer512 Nov 28 '21 at 12:54
  • I marked your answer as correct it was obligatory for me. Yes it is true that print() in these cases is useful I had completely forgotten. I was taken down my reputation because I misspoke my question. The old ones are hard on the new ones ... Thank you again very much for your answer. – X coder Nov 28 '21 at 13:00
  • You don't see my extra point because I don't have enough reputation right now, sorry for that. The elders should have more understandings ... It's a shame. – X coder Nov 28 '21 at 13:00
  • 1
    @Xcoder - you can also try out in this great platform for small program execution's to see each steps `changes` in variables - https://pythontutor.com/ – Daniel Hao Nov 28 '21 at 13:31
  • Another good S/O explained this - https://stackoverflow.com/questions/20639180/ – Daniel Hao Nov 28 '21 at 15:13