>>> import itertools
>>> n = [1,2,3,4]
>>> combObj = itertools.combinations(n,3)
>>>
>>> combObj
<itertools.combinations object at 0x00000000028C91D8>
>>>
>>> list(combObj)
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>>
>>> for i in list(combObj): #This prints nothing
... print(i)
...
-
How can i iterate through combObj ?
-
How can i convert
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
to
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
Once you iterate through the
itertools.combinationsobject once, it’s been used up and you can’t iterate over it a second time.If you need to reuse it, the proper way is to make it a
listortupleas you did. All you need to do is give it a name (assign it to a variable) so it sticks around.If you want to iterate over it just once, you just don’t call
liston it at all:Side note: The standard way to name object instances / normal variables would be
comb_objrather thancombObj. See PEP-8 for more info.To convert the inner
tuples tolists, use a list comprehension and thelist()built-in: