Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do i use itertools?

I am trying to make a list containing all possible variations of 1 and 0. like for example if I have just two digits I want a list like this:

[[0,0], [0,1], [1,0], [1,1]]

But if I decide to have 3 digits I want to have a list like this:

[[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1,1]]

Someone told me to use itertools, but I cannot get it to work the way I want.

>>> list(itertools.permutations((range(2))))
[(0, 1), (1, 0)]
>>> [list(itertools.product((range(2))))]
[[(0,), (1,)]]

Is there a way to do this? And question number two, how would i find documentation on modules like this? I am just flailing blindly here

like image 943
Kaizer von Maanen Avatar asked Jul 18 '13 12:07

Kaizer von Maanen


People also ask

Why do we use Itertools in Python?

Itertools is a module in python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module incorporates functions that utilize computational resources efficiently.

Do I need to import Itertools?

Requirements. We must import the itertools module before we can use it. We will also import the operator module. This module is not necessary when using itertools , it is only needed for some of the examples below.

Is Itertools built into to Python?

Introduction. itertools is a built-in module in Python for handling iterables. It provides a number of fast, memory-efficient way of looping through iterables to achieve different desired results.


2 Answers

itertools.product(.., repeat=n)

>>> import itertools
>>> list(itertools.product((0,1), repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

Python Module Index contains links for standard library modules documentation.

like image 170
falsetru Avatar answered Nov 15 '22 11:11

falsetru


itertools.product() can take a second argument: the length. It defaults to one, as you have seen. Simply, you can add repeat=n to your function call:

>>> list(itertools.product(range(2), repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

To find the docs, you can either use help(itertools) or just do a quick google (or whatever your search engine is) search "itertools python".

like image 35
TerryA Avatar answered Nov 15 '22 09:11

TerryA