0

Is there a one-liner or Pythonic (I'm aware that the former doesn't necessarily imply the latter) way to write the following nested loop?

for i in some_list:
    for j in i:
        # do something

I've tried

import itertools
for i,j in itertools.product(some_list,i):
    # do something

but I get a 'reference before assignment error', which makes sense, I think. I've been unable to find an answer to this question so far... Any suggestions? Thanks!

  • Use list complehension it will use as onliner instead of loop in pythonic way. – Nilesh Aug 04 '14 at 10:17
  • 1
    @Lafada: nested list comprehensions are not that pythonic (they can be hard to read), **and** in any way using list comprehensions for side effects is definitly unpythonic. – bruno desthuilliers Aug 04 '14 at 10:21

2 Answers2

1

If you want to iterate through each sub-list in some_list in turn you can use itertools.chain:

for j in itertools.chain(*some_list):

A short demo:

>>> import itertools
>>> some_list = [[1, 2], [3, 4]]
>>> for j in itertools.chain(*some_list):
    print j


1
2
3
4

Alternatively there is chain.from_iterable:

>>> for j in itertools.chain.from_iterable(some_list):
    print j


1
2
3
4

(Aside from the slight syntax change, see this question for an explanation of the difference.)

Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • You mean I can still use this for dictionaries? I can see how it works for lists of lists, but don't see how it would work for a list of dictionaries. Could you show me please? –  Aug 04 '14 at 12:48
  • The answer is "it depends". For what you're trying to do, no, although if you just wanted to iterate over the list values you could do `for j in itertools.chain.from_iterable(map(itemgetter("some_key"), some_list)): print j`. – jonrsharpe Aug 04 '14 at 12:49
1

Use chain:

import itertools


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

for i in itertools.chain(*some_list):
    print i
1
2
3
4
3
4
5
6
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321