ArtisanSamosa
ArtisanSamosa

Reputation: 877

Can someone explain this program to me?

What does the following expression produce as a value:

[(x, x*y) for x in range(2) for y in range(2)]
  1. [(0,0), (0,1), (1,0), (1,1)]

  2. [0, 1, 2]

  3. [(0,0), (1,0), (0,0), (1,1)]

  4. [(0,0), (0,0), (1,0), (1,1)]

  5. None of the above

The answer is 4, but I don't understand why.

Upvotes: 0

Views: 198

Answers (4)

Swiss
Swiss

Reputation: 5829

Assuming python 2.

range(2) returns the list [0, 1]

[(x, x*y) for x in [0, 1] for y in [0,1]]

Thus x and y will be all combinations of the lists [0, 1] and [0, 1]

[(x, x*y) for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]]

x    y    x*y    (x, x*y)
0    0    0      (0, 0)
0    1    0      (0, 0)
1    0    0      (1, 0)
1    1    1      (1, 1)

Upvotes: 2

intuited
intuited

Reputation: 24044

Nested list comprehensions work in the same way as if you had written for loops like that.

So your example list comprehension works like this generator function:

def example():
    for x in range(2):
        for y in range(2):
            yield (x, x*y)

Upvotes: 1

Tyler Carter
Tyler Carter

Reputation: 61567

Read this as

list = [];
for x in range(2):
  for y in range(2):
    list.append((x, x*y))

Basically it will iterate 4 times with the following X,Y values

X=0, Y=0
X=0, Y=1
X=1, Y=0
X=1, Y=1

Zero times anything will always be zero, so you get your 4 arrays

First Index = 0, 0*0
Second Index = 0, 0*1
Third Index = 1, 1*0
Fourth Index = 1, 1*1

Upvotes: 1

Anycorn
Anycorn

Reputation: 51465

read as:

for x in range(2): # 0,1
  for y in range(2): # 0,1
     (x, x*y)

Upvotes: 2

Related Questions