Search code examples
pythonpython-itertools

Python creating a list with itertools.product?


I'm creating a list with itertools from a list of ranges, so far I have this:

start_list = [xrange(0,201,1),xrange(0,201,2),xrange(0,201,5),xrange(0,201,10),xrange(0,201,20),xrange(0,201,50),xrange(0,201,100),xrange(0,201,200)]

Now, I know that if I were to try to run this next line it will kill my python interpreter:

next_list = list(itertools.product(*start_list))

What I'm wondering is would it be possible to put in an argument that checks each tuple, for a sum of its items and only puts them in next_list if equal to a certain amount?

Maybe something like:

next_list = list(itertools.product(*start_list,sum(tuples)=200))

I know this isn't right and I might need to start to re-think the way I'm going about this. Will start_list's ranges in the generator be too many to get through to build another list?


Solution

  • Better to just use a list comprehension

    new_list = [item for item in itertools.product(*start_list) if sum(item) == 200]