Flattening lists

Shane Geiger sgeiger at councilforeconed.org
Thu Feb 5 15:10:06 CET 2009


These functions come from goopy:


def flatten1(seq):
  """
  Return a list with the contents of SEQ with sub-lists and tuples 
"exploded".
  This is only done one-level deep.
  """

  lst = []
  for x in seq:
    if type(x) is list or type(x) is tuple:
      for val in x:
        lst.append(val)
    else:
      lst.append(x)
  return lst

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




Brian Allen Vanderburg II wrote:
> mrkafk at gmail.com wrote:
>> Hello everybody,
>>
>> Any better solution than this?
>>
>> def flatten(x):
>>     res = []
>>     for el in x:
>>         if isinstance(el,list):
>>             res.extend(flatten(el))
>>         else:
>>             res.append(el)
>>     return res
>>
>> a = [1, 2, 3, [4, 5, 6], [[7, 8], [9, 10]]]
>> print flatten(a)
>>
>>
>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>
>> Regards,
>> mk
>>
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
>
> I think it may be just a 'little' more efficient to do this:
>
> def flatten(x, res=None):
>    if res is None:
>       res = []
>
>    for el in x:
>       if isinstance(el, (tuple, list)):
>          flatten(el, res)
>       else:
>          res.append(el)
>
>    return res
>
> Brian Vanderburg II
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>


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