January 21st, 2014, 02:26 PM

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]]
January 21st, 2014, 02:49 PM

Do you understand how array works and how it is indexed? that the first arrayindex start at 0?
With a range of 3 for both x and y, you are actually creating a twodimensional array with space for nine numbers; this can be displayed in a grid/table like structure as this:
Then try to do the multiplication and/or addition manually for each index and compare them to the numbers you posted.
January 21st, 2014, 03:04 PM

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]]
January 21st, 2014, 03:25 PM

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]]
>>>
Please note that in your first post i had a prior value of 2.
>>> i = 2
>>> print([i*j for j in range(3)])
[0, 2, 4]
>>> del i
>>> print([i*j for j in range(3)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
NameError: global name 'i' is not defined
>>>
[code]
Code tags[/code] are essential for python code and Makefiles!