I’m a very novice programmer. I’m trying to use the combinations tool in the itertools module. So I try:
from itertools import *
print combinations('12345', 3)
but instead of the expected ('123', '124', '125', [...]) I get <itertools.combinations object at [pointer]>. I am very confused because calling methods in other modules returns the expected result, for instance:
import random
print random.randrange(10)
>>> 9
What am I doing wrong with the itertools module?
Nothing. The result is what it should be. What you’re apparently not accounting for is that the result is an iterator, not a fully evaluated list/tuple of results. The output you see is the
repr()of that object (it’s not returning a string). You can convert the former into the latter by passing it to thelistconstructor:But when you don’t need that and you just iterate over the values, it saves a lot of memory by not storing all results at the same time. It also permits avoiding work by not consuming the whole iterator (for example, finding the first combination satisfying some condition and then returning).