list comprehension question

Shane Geiger sgeiger at councilforeconed.org
Fri May 1 12:24:05 EDT 2009


from goopy.functional import flatten  # 
http://sourceforge.net/projects/goog-goopy/
b = [(1,2), (3,4), (5,6)]
print flatten(b)



#from goopy.functional import flatten  # 
http://sourceforge.net/projects/goog-goopy/

def flatten(seq):
  """
  Returns a list of the contents of seq with sublists and tuples "exploded".
  The resulting list does not contain any sequences, and all inner sequences
  are exploded.  For example:

  >>> flatten([7,(6,[5,4],3),2,1])
  [7,6,5,4,3,2,1]
  """
  lst = []
  for el in seq:
    if type(el) == list or type(el) is tuple:
      lst.extend(flatten(el))
    else:
      lst.append(el)
  return lst



Chris Rebert wrote:
> On Thu, Apr 30, 2009 at 5:56 PM, Ross <ross.jett at gmail.com> 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?
>>     
>
> Your comprehension is the identity comprehension (i.e. it effectively
> just copies the list as-is).
> What you're trying to do is difficult if not impossible to do as a
> comprehension.
>
> Here's another approach:
> b = list(itertools.chain.from_iterable(a))
>
> And without using a library function:
> b = []
> for pair in a:
>     for item in pair:
>         b.append(item)
>
> Cheers,
> Chris
>   


-- 
Shane Geiger, IT Director
Council For Economic Education / www.councilforeconed.org
sgeiger at councilforeconed.org  / 402-438-8958

Teaching Opportunity




More information about the Python-list mailing list