1

This might be simple, but I got stuck for quite some time.

I was trying to iterate two combinations. But it didn't go through all the items.

itt_1 = [1, 2, 3] 
comb_1 = combinations(itt, 2)
itt_2 = ['a', 'b', 'c']
comb_2 = combinations(itt_2, 2)
count = 0
for ii in list(comb_1):
    for jj in list(comb_2):
        print ii, jj

I expected to see 9 printout results. But instead, whether or not I used list function, it only shows the first 3 of them, see below:

(1, 2) ('a', 'b')
(1, 2) ('a', 'c')
(1, 2) ('b', 'c')

I believe there is something to do with the combinations, as it is a generator to be used in iterations and can be used only once. Does that mean, it cannot be used in nested for loop? Why does it only print the first combination of comb_1 in the above example?

Puluoning
  • 15
  • 5
  • Related (likely dupe): https://stackoverflow.com/questions/44420135/filter-object-becomes-empty-after-iteration/44420191#44420191 – cs95 Dec 27 '18 at 18:58

1 Answers1

0

I think the reason is that inside the inner loop it somehow looses the track of comb_2: run this:

itt_1 = [1, 2, 3] 
comb_1 = combinations(itt_1, 2)
itt_2 = ['a', 'b', 'c']
comb_2 = combinations(itt_2, 2)
count = 0
for ii in list(comb_1):
    print ii
    for jj in list(comb_2):
        print ii, jj

and you will get following result which predicts the same:

(1, 2)
(1, 2) ('a', 'b')
(1, 2) ('a', 'c')
(1, 2) ('b', 'c')
(1, 3)
(2, 3)

try converting them into lists beforehand. this works for me:

itt_1 = [1, 2, 3]
comb_1 = list(combinations(itt_1, 2))
itt_2 = ['a', 'b', 'c']
comb_2 = list(combinations(itt_2, 2))
for ii in comb_1:
    for jj in comb_2:
        print ii, jj

Result:

(1, 2) ('a', 'b')
(1, 2) ('a', 'c')
(1, 2) ('b', 'c')
(1, 3) ('a', 'b')
(1, 3) ('a', 'c')
(1, 3) ('b', 'c')
(2, 3) ('a', 'b')
(2, 3) ('a', 'c')
(2, 3) ('b', 'c')
  • This makes sense. In fact, I did the same thing to fix the issue. But I just try to understand why it was the case. – Puluoning Dec 27 '18 at 21:23