0

when I use combinations from itertools, I find that I can only use it once, and afterwards I must repeat the line of code for it to work again. For example,

from itertools import combinations
comb = combinations( range( 0 , 5 ) , 2 )
xyLabels = [ (f'PCA{x}', f'PCA{y}') for x , y in  comb ]

>[('PCA0', 'PCA1'), ('PCA0', 'PCA2'), ('PCA0', 'PCA3'), ('PCA0', 'PCA4'), ('PCA1', 'PCA2'), ('PCA1', 'PCA3'), ('PCA1', 'PCA4'), ('PCA2', 'PCA3'), ('PCA2', 'PCA4'), ('PCA3', 'PCA4')]

Whereas If I do the following:

comb = combinations( range( 0 , 5 ) , 2 )
xyLabels = [ (f'PCA{x}', f'PCA{y}') for x , y in  comb ]
yxLabels = [ (f'PCA{x}', f'PCA{y}') for x , y in  comb ]
print(yxLabels)
> []

Printing the secod argument will only produce an empty list. However, to solve this I have to do the following:

comb = combinations( range( 0 , 5 ) , 2 )
xyLabels = [ (f'PCA{x}', f'PCA{y}') for x , y in  comb ]
comb = combinations( range( 0 , 5 ) , 2 )
yxLabels = [ (f'PCA{x}', f'PCA{y}') for x , y in  comb ]
print(yxLabels)

What is the reason behind it and how can I get it to work with only one comb?

tesla john
  • 310
  • 1
  • 2
  • 9
  • Iterating over `comb` the first time consumes all the data, and so it is empty after that. – John Gordon Nov 19 '22 at 23:40
  • @JohnGordon ah okay, how can I store the content inside another variable so that I won't have to re-use comb? – tesla john Nov 19 '22 at 23:42
  • @JohnGordon It looks like the following holds for me: ```new_comb = copy.copy(comb)``` – tesla john Nov 19 '22 at 23:43
  • Calling `combinations` is cheap precisely because it doesn't do much of anything until you start iterating over it. `combinations(range(0, 5), 2)` is probably no more expensive than `copy.copy(comb)`. – chepner Nov 20 '22 at 00:00

1 Answers1

0

You need to define comb as a list instead of a generator - like this:

comb = list(combinations( range( 0 , 5 ) , 2 ))

That will then give you the result you expect. it will however increase your memory utilisation because you evaluate comb fully, instead of having it wait in the wings to hand you values on demand. Whether the memory/convenience tradeoff is worth it is your call.

Vin
  • 929
  • 1
  • 7
  • 14