Search code examples
pythonpython-itertools

Problem importing itertools saying itertools not defined


Thank you to all who helped me with this question. I didn't post my entire code because I figured the line "import itertools" was implied and that the other lines did not pertain to the issue at hand. I found out that in the IDE I'm using, there is actually a button to search and download certain packages. Without doing that first it doesn't import any package. Then there was the secondary question embedded here. Namely, how to produce all 3 word combinations without repetition. That problem was also solved by user19077881. Thank you very much. I don't quite understand the proper etiquette here yet. I'm at the very early stages of learning. So I appreciate all of your feedback Anerdw. I'm trying to build an algorithm that will return all possible 3 word combinations of an existing list with 278 words in it. But I've hit a wall.

for i in range(1, len(lst)+1):
    words.append(i)
    els = [list(x) for x in itertools.combinations(lst, i)]
    words.append(els)

When I run it, it keeps telling me itertools is not defined.


Solution

  • Using itertools.combinations you should specify the combinations sizing (3 in your case). To use a simple example:

    import itertools
    
    s = ['one', 'two', 'three', 'four', 'five']
    
    result = list(itertools.combinations(s, 3))
    
    print(result)
    

    gives a List of Tuples with each combination:

    [('one', 'two', 'three'), ('one', 'two', 'four'), ('one', 'two', 'five'), ('one', 'three', 'four'), ('one', 'three', 'five'), ('one', 'four', 'five'), ('two', 'three', 'four'), ('two', 'three', 'five'), ('two', 'four', 'five'), ('three', 'four', 'five')]
    

    or you can iterate to get each one in turn:

    result = itertools.combinations(s, 3)
    
    for combi in result:
        print(combi)