Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How to do it...

The Cartesian product is usually what people think of when talking about combinations and permutations.

  1. Given a set of elements, A, B, and C, we want to extract all possible couples of two elements, AA, AB, AC, and so on:
>>> import itertools
>>> c = itertools.product(('A', 'B', 'C'), repeat=2)
>>> list(c)
[('A', 'A'), ('A', 'B'), ('A', 'C'),
 ('B', 'A'), ('B', 'B'), ('B', 'C'), 
 ('C', 'A'), ('C', 'B'), ('C', 'C')]
  1. In case you want to omit the duplicated entries (AA, BB, CC), you can just use permutations:
>>> c = itertools.permutations(('A', 'B', 'C'), 2)
>>> list(c)
[('A', 'B'), ('A', 'C'), 
 ('B', 'A'), ('B', 'C'), 
 ('C', 'A'), ('C', 'B')]
  1. You might even want to ensure that the same couple doesn't happen twice (such as ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content