#1
  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. #2
  3. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,663
    Rep Power
    1958
    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.
  4. #3
  5. 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]]
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,895
    Rep Power
    481
    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!

IMN logo majestic logo threadwatch logo seochat tools logo