From: Tycho Andersen on 8 May 2010 17:00 On Sat, May 8, 2010 at 3:41 PM, Oltmans wrote:> Hi, I've a list that looks like following > > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: >        for a in i: >                print a > > but I was wondering if there is a shorter, more elegant way to do it? How about itertools? In python 2.6: >>> a = [ [1,2,3,4], [5,6,7,8] ] >>> from itertools import chain >>> for i in chain(*a): .... print i .... 1 2 3 4 5 6 7 8 From: Oltmans on 8 May 2010 17:06 On May 9, 1:53 am, superpollo wrote: > add = lambda a,b: a+b > for i in reduce(add,a): >      print i This is very neat. Thank you. Sounds like magic to me. Can you please explain how does that work? Many thanks again. From: Günther Dietrich on 8 May 2010 17:09 Tycho Andersen wrote: >On Sat, May 8, 2010 at 3:41 PM, Oltmans wrote: >> Hi, I've a list that looks like following >> >> a = [ [1,2,3,4], [5,6,7,8] ] >> >> Currently, I'm iterating through it like >> >> for i in [k for k in a]: >>        for a in i: >>                print a >> >> but I was wondering if there is a shorter, more elegant way to do it? > >How about itertools? In python 2.6: > >>>> a = [ [1,2,3,4], [5,6,7,8] ] >>>> from itertools import chain >>>> for i in chain(*a): >... print i >... >1 >2 >3 >4 >5 >6 >7 >8 Why not this way? >>> a = [[1,2,3,4], [5,6,7,8]] >>> for i in a: .... for j in i: .... print(j) .... 1 2 3 4 5 6 7 8 Too simple? Best regards, Günther From: Tycho Andersen on 8 May 2010 17:40 On Sat, May 8, 2010 at 4:09 PM, Günther Dietrich wrote: [snip]> Too simple? No, not at all. I really only intended to point the OP to itertools, because it does lots of useful things exactly like this one. \t From: Lie Ryan on 9 May 2010 01:17 On 05/09/10 07:09, Günther Dietrich wrote:> > Why not this way? > >>>> a = [[1,2,3,4], [5,6,7,8]] >>>> for i in a: > .... for j in i: > .... print(j) > .... > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > > Too simple? IMHO that's more complex due to the nested loop, though I would personally do it as: a = [ [1,2,3,4], [5,6,7,8] ] from itertools import chain for i in chain.from_iterable(a): print i so it won't choke when 'a' is an infinite stream of iterables. First  |  Prev  |  Next  |  Last Pages: 1 2 3 Prev: [ANN] Pyspread 0.1.1 releasedNext: A more general solution