Python returning `<itertools.combinations object at 0x10049b470>` – How can I access this?

Question:

I have this simple piece of code that returns what’s in the title. Why doesn’t the array simply print? This is not just an itertools issue I’ve also noticed it for other code where it’ll just return the object location.

Here is the code. I’m running 2.7.1, an enthought distribution (pylab) – using it for class.

import itertools

number = [53, 64, 68, 71, 77, 82, 85]

print itertools.combinations(number, 4)
Asked By: tshauck

||

Answers:

It doesn’t print a simple list because the returned object is not a list. Apply the list function on it if you really need a list.

print list(itertools.combinations(number, 4))

itertools.combinations returns an iterator. An iterator is something that you can apply for on. Usually, elements of an iterator is computed as soon as you fetch it, so there is no penalty of copying all the content to memory, unlike a list.

Answered By: kennytm

Try this:

for x in itertools.combinations(number, 4):
   print x

Or shorter:

results = [x for x in itertools.combinations(number, 4) ]

Basically, all of the itertools module functions return this type of object. The idea is that, rather than computing a list of answers up front, they return an iterable object that ‘knows’ how to compute the answers, but doesn’t do so unless `asked.’ This way, there is no significant up front cost for computing elements. See also this very good introduction to generators.

Answered By: phooji

Beside the proposed solutions, other ways, with a little change to your code, you can do:

1)

import itertools

number = [53, 64, 68, 71, 77, 82, 85]

res = itertools.combinations(number, 4)

print(*res)

Put the result of the combination into a variable (res), after, with print, use a single asterisks * to unpacks the sequence/collection into positional arguments. More detail is in here.

2)

import itertools

number = [53, 64, 68, 71, 77, 82, 85]

*res, = itertools.combinations(number, 4)

print(res)

This in python 3, it called "Extended Iterable Unpacking"

A good tutorials about using Asterisks (*, **) in here.

Answered By: ibra
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.