list comprehensions whats happening here

Jeremy Hylton jeremy at digicool.com
Fri Apr 13 18:15:54 EDT 2001


>>>>> "CR" == Carlos Ribeiro <cribeiro at mail.inet.com.br> writes:

  CR> I also lost. I did a small change on your example to better
  CR> illuminate what is happening:

  >>>> [[i,j] for i in range(3), for j in 'abc']
  CR> [[[0, 1, 2], 'a'], [[0, 1, 2], 'b'], [[0, 1, 2], 'c']]
  >>>> [[i,j] for i in range(3), for j in 'abc',]
  CR> [[[0, 1, 2], 'abc']]
  >>>> [[i,j] for i in range(3) for j in 'abc']
  CR> [[0, 'a'], [0, 'b'], [0, 'c'], [1, 'a'], [1, 'b'], [1, 'c'], [2,
  CR> 'a'], [2, 'b'], [2, 'c']]

  CR> And also, a fourth case for completeness:

  >>>> [[i,j] for i in range(3) for j in 'abc',]
  CR> [[0, 'abc'], [1, 'abc'], [2, 'abc']]

  CR> So it seems that the idiom

  CR>    for i in range(x),

  CR> with the comma right after the for clause, "reduces" the
  CR> iterated list to the original list again, and then apply it to
  CR> all further iterations of the list comprehension. Now, I don't
  CR> know if this is by design or by accident; all I know is that
  CR> this is something that may be exploited as a useful idiom. For
  CR> instance, neither map or zip have this behavior, of applying the
  CR> same list to all members of the other.

I think it would be hard to say that this was "by design" but it makes
sense after you stare at it for a while <0.5 wink>.

The "range(x)," is being interpreter as the length-1 tuple containing
the value of range(x).  The for loop iterates over the (single) value
in the tuple.

Jeremy





More information about the Python-list mailing list