list comprehension question

Michael Spencer mahs at telcopartners.com
Thu Apr 30 21:18:44 EDT 2009


Ross wrote:
> If I have a list of tuples a = [(1,2), (3,4), (5,6)], and I want to
> return a new list of each individual element in these tuples, I can do
> it with a nested for loop but when I try to do it using the list
> comprehension b = [j for j in i for i in a], my output is b =
> [5,5,5,6,6,6] instead of the correct b = [1,2,3,4,5,6]. What am I
> doing wrong?
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


  >>> a = [(1,2), (3,4), (5,6)]
  >>> [i for t in a for i in t]
  [1, 2, 3, 4, 5, 6]

Or, with different spacing to make the nesting clearer:

  >>> [i
  ...     for t in a
  ...         for i in t]
  [1, 2, 3, 4, 5, 6]
  >>>

Michael




More information about the Python-list mailing list