Search code examples
pythonpython-itertools

Python Capitalization elements in a list (using Itertools?)


I have a list containing integers which indicate how many capitalization will occur at once in a list.

x = [1, 2]
# when x == 1 then 1 capitalization per time
# when x == 2 then 2 capitalization per time
l = ['a', 'b', 'c']

the output would be like so...

Abc
aBc
abC
ABc
AbC
aBC

I can code this normally, but can it be done through itertools?


Solution

  • Use itertools.combinations to pick the indices of the letters to capitalize:

    from itertools import combinations
    
    
    x = [1, 2]
    l = ['a', 'b', 'c']
    
    
    for xi in x:
        for comb in combinations(range(len(l)), xi):
            print("".join([e.upper() if i in comb else e for i, e in enumerate(l) ]))
    

    Output

    Abc
    aBc
    abC
    ABc
    AbC
    aBC