chevron_left
itertools
check_circle
Mark as learned thumb_up
0
thumb_down
0
chat_bubble_outline
0
auto_stories new
settings
Getting all possible combinations of elements in Python
Standard Library
chevron_rightitertools
schedule Jul 1, 2022
Last updated local_offer Python
Tags tocTable of Contents
expand_more Check out the interactive map of data science
We can use combinations
within the itertools
module to get all the possible combinations of elements in a sequence in Python.
To get all the possible pair combinations from my_list
:
from itertools import combinations
cards = ['Ace', 'King', 'Queen', 'Jack']pair_obj = combinations(cards, 2)
pairs = [*pair_obj] #unpacking into a listprint(pairs)
[('Ace', 'King'), ('Ace', 'Queen'), ('Ace', 'Jack'), ('King', 'Queen'), ('King', 'Jack'), ('Queen', 'Jack')]
In the above example we generated combinations of 2, however, this can be specified accordingly:
itertools.combinations(iterable, r)
To generate combinations of 3 from my_list
:
from itertools import combinations
cards = ['Ace', 'King', 'Queen', 'Jack']pair_obj = combinations(cards, 3)
pairs = [*pair_obj] #unpacking into a listprint(pairs)
[('Ace', 'King', 'Queen'), ('Ace', 'King', 'Jack'), ('Ace', 'Queen', 'Jack'), ('King', 'Queen', 'Jack')]
Published by Arthur Yanagisawa
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!