From: Oltmans on 8 May 2010 16:41 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? From: superpollo on 8 May 2010 16:53 Oltmans ha scritto:> 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: i think you used te a identifier for two meanings... > print a > > but I was wondering if there is a shorter, more elegant way to do it? add = lambda a,b: a+b for i in reduce(add,a): print i From: Chris Rebert on 8 May 2010 16:55 On Sat, May 8, 2010 at 1: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? Just use a different variable name besides `a` in the nested loop so you don't have to make the copy of `a`. I arbitrarily chose `b`: for i in a: for b in i: print b Cheers, Chris -- http://blog.rebertia.com From: superpollo on 8 May 2010 16:56 superpollo ha scritto:> Oltmans ha scritto: >> 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: > > i think you used te a identifier for two meanings... > >> print a >> >> but I was wondering if there is a shorter, more elegant way to do it? > > > add = lambda a,b: a+b or: from operator import add > for i in reduce(add,a): > print i From: Alain Ketterlin on 8 May 2010 16:56 Oltmans writes: > 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 I would prefer: for i in a: for v in i: print v i.e., not messing with a and avoiding an additional list. > but I was wondering if there is a shorter, more elegant way to do it? I can't see any, but if you need to save space, you may use for v in (e for l in a for e in l): ... -- Alain.  |  Next  |  Last Pages: 1 2 3 Prev: [ANN] Pyspread 0.1.1 releasedNext: A more general solution