1

I followed the top solution to Flattening an irregular list of lists in python (Flatten (an irregular) list of lists) using the following code:

def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
            for sub in flatten(el):
                yield sub
        else:
            yield el


L = [[[1, 2, 3], [4, 5]], 6]

L=flatten(L)
print L

And got the following output:

"generator object flatten at 0x100494460"

I'm not sure which packages I need to import or syntax I need to change to get this to work for me.

Community
  • 1
  • 1
Atticus29
  • 4,190
  • 18
  • 47
  • 84

2 Answers2

5

You can iterate the generator object directly:

for x in L:
    print x

or if you truly need a list, you can make one from it:

list(L)
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
5

functions with the yield keyword return generators. e.g.

>>> def func():
...     for x in range(3):
...         yield x
... 
>>> a = func()
>>> print a
<generator object func at 0xef198>
>>> next(a)
0
>>> next(a)
1
>>> next(a)
2
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 
>>>
>>> for x in func():
...     print x
... 
0
1
2

In other words, they evaluate lazily, only giving you values as you request them in iteration. The best way to construct a list out of a generator is to use the list builtin.

print list(L)
mgilson
  • 300,191
  • 65
  • 633
  • 696