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!

2
  • Use list complehension it will use as onliner instead of loop in pythonic way. Commented Aug 4, 2014 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. Commented Aug 4, 2014 at 10:21

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments