loop 'for' and function range

A forum for general discussion of the Python programming language.

loop 'for' and function range

Postby giny28 » Tue Jan 21, 2014 7:41 pm

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 :cry: :
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

Postby stranac » Tue Jan 21, 2014 7:56 pm

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]]

The second example you ask about would give you:
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.
User avatar
stranac
 
Posts: 1144
Joined: Thu Feb 07, 2013 3:42 pm

Re: loop 'for' and function range

Postby Marbelous » Tue Jan 21, 2014 8:32 pm

Marbelous
 
Posts: 141
Joined: Fri May 31, 2013 8:12 pm


Return to General Discussions

Who is online

Users browsing this forum: No registered users and 2 guests