Two small modules that solve very specific tasks: itertools generates combinations of elements and string offers ready-made collections of characters.
string: collections of characters
import string
print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_letters) # abc...xyzABC...XYZ
print(string.digits) # 0123456789
print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
They are simple texts: you can loop over them, concatenate them or check whether a character belongs to them:
allowed = string.ascii_lowercase + string.digits
print("a" in allowed) # True
print("A" in allowed) # False
print(len(allowed)) # 36
Random passwords with random and string
import random
import string
characters = string.ascii_letters + string.digits
password = ""
for _ in range(8):
password += random.choice(characters)
print(len(password)) # 8
print(password.isalnum()) # True
itertools: combining elements
itertools returns its results as iterators: you loop over them with a for or turn them into a list with list().
from itertools import permutations
for p in permutations("abc"):
print("".join(p))
# abc
# acb
# bac
# bca
# cab
# cba
print(list(permutations([1, 2, 3], 2)))
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
from itertools import combinations
print(list(combinations(["a", "b", "c"], 2)))
# [('a', 'b'), ('a', 'c'), ('b', 'c')]
from itertools import product
print(list(product([1, 2], ["x", "y"])))
# [(1, 'x'), (1, 'y'), (2, 'x'), (2, 'y')]
print(len(list(product("01", repeat=3)))) # 8 (all 3-digit binary numbers)
| Function | What it generates | With "abc" two at a time |
|---|---|---|
permutations | orderings, order matters | 6 |
combinations | groups, order does not matter | 3 |
product | all pairs with repetition | 9 |
If you only need to know how many there are, math.perm and math.comb calculate it without generating them.
Permutations with repeated letters
If the word has repeated letters, permutations generates repeated orderings. A set removes them:
words = set()
for p in permutations("aab"):
words.add("".join(p))
print(sorted(words)) # ['aab', 'aba', 'baa']
Practice in Password generator and Anagrams.