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.
>Solution :
Lets take it step by step.
-
test = ['x' for i in range(9)].testhere is a list that contains 9'x's -
[test[i*3: (i+1)*3] for i in range(3)]. Lets call this list a temp_list. This list comprehension takes a slice oftestlist. Foriequals to 0, the slice will betest[0: 3]which is equals to['x', 'x', 'x']. Foriequals to 1, the slice will betest[3: 6]but contains same values as before. -
Now
for row in .... This will loop over what we designated temp_list for better denoting. So this loop will iterate 3 times androwevery time will be['x', 'x', 'x']. So theprint(..)will be repeated 3 times -
print('1 ' + ' 2 '.join(row) + ' 3'). Thestr.join()actually concatenates every element of an iterable (here a list calledrow) withstr(here ‘ 2 ‘) acting as a separator between them. So,' 2 'join(row)here will produce outputx 2 x 2 xand finally theprint()will print1 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