Thread: Loop 'for' and function range

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jan 2014
Posts
9
Rep Power
0

Loop 'for' and function range

Hello,

_I didn't understand the functional approach with the loop'for'. Could you explain me that?
Code:
```
>>> 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:
```>>> 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]]
2. Do you understand how array works and how it is indexed? that the first array-index start at 0?

With a range of 3 for both x and y, you are actually creating a two-dimensional array with space for nine numbers; this can be displayed in a grid/table like structure as this:
Code:
```y\x 0 1 2
0
1
2```
Then try to do the multiplication and/or addition manually for each index and compare them to the numbers you posted.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jan 2014
Posts
9
Rep Power
0
Thanks for your explanation , i know how an array works .

if i have to create the matrix Z = [[1,2,3],[4,5,6]] (2 lines and 3 columns), and to use that special loop but my codes don't work good :

Code:
```>>> squares = []
>>> for x in range(6):
squares.append(x+1)
Z = [squares]

>>> Z
[[1, 2, 3, 4, 5, 6]]
>>> squares
[1, 2, 3, 4, 5, 6]

>>> [[x+1 for x in range(6)]]
[[1, 2, 3, 4, 5, 6]]

>>> [[x+1 for x in range(6)]]
[[1, 2, 3, 4, 5, 6]]
>>> [[x+y for x in range(1,4)] for y in range(0,2)]
[[1, 2, 3], [2, 3, 4]]```
4. Code:
```>>> [[x+y*3 for x in range(1,4)] for y in range(0,2)]
[[1, 2, 3], [4, 5, 6]]
>>> [[x+y for x in range(1,4)] for y in range(0,6,3)]
[[1, 2, 3], [4, 5, 6]]
>>>```