Home > OS >  Python List comprehension PCEP questions
Python List comprehension PCEP questions

Time:01-18

I recently came across a list comprehension questions in practice exams and although I have the correct answer I don't understand how those answers are valid. Question: How many stars (*) will the following snippet send to the console?

lst = [[c for c in range(r)] for r in range(3)]
   for x in lst:
      for y in x:
         if y < 2:
            print('*', end='')

My answer was 2 stars. My thinking is that lst = [0,1,2]. x and lst should be the same number of elements - 0,1,2. Only 0, 1 are <2, fulfilling the condition. However, the answer is 3. I've verified on python tutor that the list = [0,0,1]. But I dont understand why. Can someone please explain?

CodePudding user response:

Consider lst = [[c for c in range(r)] for r in range(3)]:

First iteration:

r = 0 => range(0) -> doesn't print anything

Second iteration:

r = 1 => range(1) -> 0 -> prints * once

Third iteration

r = 2 => range(2) -> 0,1 -> prints * twice

CodePudding user response:

Indeed it will print "***" star .One star in second iteration and two star in third iteration.

  •  Tags:  
  • Related