[Python] Outputs all combinations of elements in the list

I want to know all the combinations of elements in the list

For example

['Apple','Orange','Grape']

From the list of

[['Apple'], ['Orange'], ['Grape'], ['Apple', 'Orange'], ['Apple', 'Grape'], ['Orange', 'Grape'], ['Apple', 'Orange', 'Grape']]

I want to get the output. Some combinations have only one element, and some have multiple elements. I know it's a list of 2 ^ n-1 answers, but when I actually tried to write it, I stumbled. Isn't it going to be a complicated nest?

I found a standard library that can be used in such cases. itertools --- Iterator generation function for efficient loop execution

Iterator argument result
combinations() p,r Tuple column of length r, no duplication in sorted order

For example

test.py


import itertools

lis = [1,2,3,4]
for pair in itertools.combinations(lis, 2):
	print(pair)

If you do the above, you will get the following results:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

For the time being, change the argument and try again.

test2.py


import itertools

lis = [1,2,3,4]
for team in itertools.combinations(lis, 3):
	print(team)
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)

With itertools.combinations (), you can get all combination patterns (in tuples) with any number of elements in the ** list like this. ** ** Here, if you start with the number of elements from 1 and turn it to the list length with a for statement, it seems that you can get the answer you wanted first.

all_combinations.py


import itertools

lis=['Apple','Orange','Grape']
result = []
for n in range(1,len(lis)+1):
	for conb in itertools.combinations(lis, n):
	    result.append(list(conb)) #Convert tuples to list type
print(result)

Execution result

[['Apple'], ['Orange'], ['Grape'], ['Apple', 'Orange'], ['Apple', 'Grape'], ['Orange', 'Grape'], ['Apple', 'Orange', 'Grape']]

If you use itertools, it seems that there will be more situations where you do not have to write nests, and it may be an essential item for paiza and competition pros. As mentioned in "Readable Code", I thought that if you make a habit of reading the standard library on a regular basis, you will be able to write good code.

It was an introduction to the standard library that I found useful!

Recommended Posts

[Python] Outputs all combinations of elements in the list
[python] Check the elements of the list all, any
Make sure all the elements in the list are the same in Python
Get the number of specific elements in a python list
[Python] Combine all the elements in the array
[Python] Sort the list of pathlib.Path in natural sort
Make a copy of the list in Python
Getting list elements in Python
[python] Get the list of classes defined in the module
[Python] Manipulation of elements in list (array) [Add / Delete]
Get the size (number of elements) of UnionFind in Python
Group by consecutive elements of a list in Python
Delete multiple elements in python list
About the basics list of Python basics
Sort and output the elements in the list as elements and multiples in Python.
How to check in Python if one of the elements of a list is in another list
Check the behavior of destructor in Python
[Python] Let's reduce the number of elements in the result in set operations
OR the List in Python (zip function)
The result of installing python in Anaconda
[python] Get the rank of the values in List in ascending / descending order
Determine if all list elements are present in the dict key
Summary of built-in methods in Python list
In search of the fastest FizzBuzz in Python
Get the EDINET code list in Python
Receive a list of the results of parallel processing in Python with starmap
Output the number of CPU cores in Python
Match the distribution of each group in Python
View the result of geometry processing in Python
Calculate the total number of combinations with python
Rewriting elements in a loop of lists (Python)
Get only the subclass elements in a list
Find the divisor of the value entered in python
Find the solution of the nth-order equation in python
The story of reading HSPICE data in Python
[Note] About the role of underscore "_" in Python
About the behavior of Model.get_or_create () of peewee in Python
Solving the equation of motion in Python (odeint)
Output in the form of a python array
Search by the value of the instance in the list
Randomly select elements from list (array) in python
Sort list elements in a specified order in Python
[Python] Manipulating elements in a list (array) [Sort]
How to remove duplicate elements in Python3 list
List of python modules
Filter List in Python
the zen of Python
Duplicate combinations in Python
List find in Python
About __all__ in python
plot the coordinates of the processing (python) list and specify the number of times in draw ()
Extract elements (using a list of indexes) in a NumPy style from a Python list / tuple
How to get a list of files in the same directory with python
Experience the good calculation efficiency of vectorization in Python
How to get the number of digits in Python
The story of FileNotFound in Python open () mode ='w'
Learn the design pattern "Chain of Responsibility" in Python
Implement the solution of Riccati algebraic equations in Python
Not being aware of the contents of the data in python
List of Python code used in big data analysis
[Python] Get the list of ExifTags names of Pillow library