## loop 'for' and function range

A forum for general discussion of the Python programming language.

### loop 'for' and function range

Hello,

_I didn't understand the functional approach with the loop'for'. Could you explain me that?

Code: Select all
`>>> F= [[x * y for x in range (3)] for y in range (3)]>>> F[[0, 0, 0], [0, 1, 2], [0, 2, 4]]`

I tried to understand with print but it does not tell me much :
Code: Select all
`>>> print([i*j for j in range(3)])[0, 2, 4]>>> print([i*j for i in range(3)])[0, 2, 4] `

_ What's the difference with the code I= [[x + y for x in range (3)] for y in range (3)] ? result [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
giny28

Posts: 4
Joined: Tue Jan 07, 2014 7:02 pm

### Re: loop 'for' and function range

Code: Select all
`F = [[x * y for x in range (3)] for y in range (3)]`

This is a nested list comprehension.
It is basically the same as writing:
Code: Select all
`F = []for y in range(3):    inner = []    for x in range(3):        inner.append(x * y)    F.append(inner)`

So this gives you as a result:
Code: Select all
`[[0*0, 1*0, 2*0], [0*1, 1*1, 2*1], [0*2, 1*2, 2*2]]`

Code: Select all
`[[0+0, 1+0, 2+0], [0+1, 1+1, 2+1], [0+2, 1+2, 2+2]]`
Friendship is magic!

R.I.P. Tracy M. You will be missed.

stranac

Posts: 1470
Joined: Thu Feb 07, 2013 3:42 pm

### Re: loop 'for' and function range

Marbelous

Posts: 195
Joined: Fri May 31, 2013 8:12 pm