How do I install the itertools package?

Viewed 34616

I wanted to try out the permutations function from the itertools module. But I keep getting the following error everytime I try to implement it:

code:

from itertools import permutations

txt=permutations('SKIN')
print(txt)

output:

<itertools.permutations object at 0x7fee48665950>

I tried using the command pip install itertools on my command prompt but I keep getting the error:

ERROR: Could not find a version that satisfies the requirement itertools (from versions: none)
ERROR: No matching distribution found for itertools

How do I install the package?

5 Answers

itertools is a built-in module no need to install it:

Help on module itertools:

NAME
    itertools - Functional tools for creating and using iterators.

FILE
    /usr/lib64/python2.7/lib-dynload/itertoolsmodu

permutations(<iterable>) returns a generator which yields successive r length permutations of elements in the iterable:

>>> type(txt)
<type 'itertools.permutations'>

>>> dir(txt)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next']

List of desired permutations:

list_perms = [ "".join(i) for i in permutations("SKIN")]

# ['SKIN', 'SKNI', 'SIKN', 'SINK', 'SNKI', 'SNIK', 'KSIN', 'KSNI', 'KISN', 'KINS', 'KNSI', 'KNIS', 'ISKN', 'ISNK', 'IKSN', 'IKNS', 'INSK', 'INKS', 'NSKI', 'NSIK', 'NKSI', 'NKIS', 'NISK', 'NIKS']

permutations() returns an object, converting it to list will do the job.

from itertools import permutations

txt=list(permutations('SKIN'))
t = [''.join(i) for i in txt]
print(t)

It works as suspected. The permutations is a generator that you can iterate over.

from itertools import permutations

txt=permutations('SKIN')
print(txt)

for single_permutation in txt:
    print(single_permutation)

you may use new version, more-intertools instead.

pip install more-itertools
  • itertools is a built-in module in python and does not need to be installed separately.
  • <itertools.permutations object at 0x7fee48665950> is not an error. It is a itterator. In order to get its content it has to be converted to list.

Possible solution is the following:

from itertools import permutations

txt = ["".join(_) for _ in permutations('SKIN')]

print(txt)

Prints

['SKIN', 'SKNI', 'SIKN', 'SINK', 'SNKI', 'SNIK', 'KSIN', 'KSNI', 'KISN', 'KINS', 'KNSI', 'KNIS', 'ISKN', 'ISNK', 'IKSN', 'IKNS', 'INSK', 'INKS', 'NSKI', 'NSIK', 'NKSI', 'NKIS', 'NISK', 'NIKS']
Related