Reputation:
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!
Upvotes: 0
Views: 446
Reputation: 180411
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
Upvotes: 1
Reputation: 122032
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.)
Upvotes: 1