Flatten an irregular 2D standard list in Python

Thing you want to do

[0, 0, [0, 0], 0, [0]]

I want to flatten a standard list that contains list irregularly like the following

[0, 0, 0, 0, 0, 0]

manner

You could do this by listing all the values once and then applying itertools.chain.from_iterable

def flatten_sequences(sequences: List[list]) -> list:
    sequences = [i if type(i) == list else [i] for i in sequences]
    flattened = list(itertools.chain.from_iterable(sequences))
    return flattened

Execution result

>>> flatten_sequences([0, 0, [0, 0], 0, [0]])
[0, 0, 0, 0, 0, 0]

Recommended Posts

Flatten an irregular 2D standard list in Python
Flatten in python
flatten in python
Sorted list in Python
List find in Python
Quicksort an array in Python 3
Solve ABC175 D in Python
Transposed matrix in Python standard
Getting list elements in Python
Extract multiple list duplicates in Python
Difference between list () and [] in Python
[python] Manage functions in a list
Write an HTTP / 2 server in Python
Develop an investment algorithm in Python 2
Make standard output non-blocking in Python
Delete multiple elements in python list
Python in is also an operator
An alternative to `pause` in Python
The story that 2D list replacement did not work in python
[Python, Julia] 3D display in Jupyter-Mayavi library
[Python] How to convert a 2D list to a 1D list
ABC 157 D --Solve Friend Suggestions in Python!
Display a list of alphabets in Python 3
OR the List in Python (zip function)
[Python] How to put any number of standard inputs in a list
Difference between append and + = in Python list
Download images from URL list in Python
Don't use \ d in Python 3 regular expressions!
Solve ABC165 A, B, D in Python
Summary of built-in methods in Python list
Get the EDINET code list in Python
[Python] Understand list slicing operations in seconds
[Python] Sort the list of pathlib.Path in natural sort
How to clear tuples in a list (Python)
Building an environment that uses Python in Eclipse
Create a standard normal distribution graph in Python
Make a copy of the list in Python
[Mac] Run the RealSense D415 sample in Python
View drug reviews using a list in Python
The trick to write flatten concisely in python
Keep key names case in Python standard ConfigParser
Randomly select elements from list (array) in python
Standard .py file used in Python trials (template)-2020
Insert an object inside a string in Python
Solve simultaneous equations in an instant using Python
Send an email with Excel attached in Python
[Python] Manipulating elements in a list (array) [Sort]
How to remove duplicate elements in Python3 list
Quadtree in Python --2
Python in optimization
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
[Python] Standard input
Epoch in Python
Discord in Python
Sudoku in Python
nCr in python