1

Given the following code:

from itertools import combinations

l_a = [1,2,3]
l_b = ["a","b","c"]
l_c = [0.1,0.2,0.3]

l_abc = [l_a,l_b,l_c]

l_com = combinations(l_abc,2)


print("l_abc t1 : ",l_abc) #t1
print("l_com t1 : ",*l_com) #t1 

print("--------------")

l_a.append(4)

print("l_abc t2 : ",l_abc) #t2 
print("l_com t2 : ",*l_com) #t2 

The output is:

l_abc t1 :  [[1, 2, 3], ['a', 'b', 'c'], [0.1, 0.2, 0.3]]                                                                                     
l_com t1 :  ([1, 2, 3], ['a', 'b', 'c']) ([1, 2, 3], [0.1, 0.2, 0.3]) (['a', 'b', 'c'], [0.1, 0.2, 0.3])                                      
--------------                                                                                                                                
l_abc t2 :  [[1, 2, 3, 4], ['a', 'b', 'c'], [0.1, 0.2, 0.3]]                                                                                  
l_com t2 : 

After the construction of a list of 3 lists (l_abc):

  1. t1: When I print the result of itertools.combinations (l_com) in time 1 (t1), it gives the correct results.
  2. t2: I modify one list (l_a) that is part of the whole list of 3 lists (l_abc). When I print again the result of the previous combinations, the results is empty.

However, you can see that, for printing only list of lists (l_abc) work fin in t1 and after the updating in t2.

Q1) Why is that, and
Q2) How I can get the correct combinations in t2 ? (naivly call again the combinations second time).

Thanks.

ibra
  • 1,164
  • 1
  • 11
  • 26
  • `*` unpacks all the values and the list becomes empty – Ajay Mar 07 '21 at 15:41
  • @Ajay, based on your comment, I have tried : `l=[1,2,3]`, `print(*l)` which gives `1 2 3`, and, `print(l)`, at the end the result is `[1,2,3]`. Which mean that the list still exist and are not empty. – ibra Mar 07 '21 at 16:05
  • 1
    https://stackoverflow.com/questions/56811623/why-does-my-generator-become-empty-after-being-iterated-through – Ajay Mar 07 '21 at 16:14
  • Many thanks @Ajay , this indeed help me (answer) the Q1. For Q2, hence, it seems that I have to call the combinations again to i) catch the updating and ii) be abale to print it. – ibra Mar 07 '21 at 17:26
  • 1
    or you can just `deep copy` the list – Ajay Mar 07 '21 at 17:31
  • yes, but with `deep copy` we loose the updating from the initial list. – ibra Mar 07 '21 at 17:37
  • 1
    `l_com = list(combinations(l_abc,2))` – Ajay Mar 07 '21 at 18:01
  • @Ajay Perfect, it works like a charm, it keep track on the update and we can print again. can you put all your suggestion comment as an answer for Q1, and Q2 ?. – ibra Mar 07 '21 at 18:11

0 Answers0