Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how does this python for loop with a loop inside the list work?

Can some one explain how this loop works?

test = ['x' for i in range(9)]
for row in [test[i*3: (i+1)*3] for i in range(3)]:
    print('1 ' + ' 2 '.join(row) + ' 3')

I thought the output would be:

1  2 x 3
1  2 x 3
1  2 x 3

I can’t follow how it inserts ‘x’ between 1 and 2.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Lets take it step by step.

  1. test = ['x' for i in range(9)]. test here is a list that contains 9 'x's

  2. [test[i*3: (i+1)*3] for i in range(3)]. Lets call this list a temp_list. This list comprehension takes a slice of test list. For i equals to 0, the slice will be test[0: 3] which is equals to ['x', 'x', 'x']. For i equals to 1, the slice will be test[3: 6] but contains same values as before.

  3. Now for row in .... This will loop over what we designated temp_list for better denoting. So this loop will iterate 3 times and row every time will be ['x', 'x', 'x']. So the print(..) will be repeated 3 times

  4. print('1 ' + ' 2 '.join(row) + ' 3'). The str.join() actually concatenates every element of an iterable (here a list called row) with str (here ‘ 2 ‘) acting as a separator between them. So, ' 2 'join(row) here will produce output x 2 x 2 x and finally the print() will print 1 x 2 x 2 x 3.

So the final output will be –

1 x 2 x 2 x 3
1 x 2 x 2 x 3
1 x 2 x 2 x 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading