How To Flatten Nested Lists in Python

Publicado el: 30 noviembre 2020
en el canal de: DataDaft
5,138
108

↓ Code Available Below! ↓

This video shows how to flatten nested lists in Python.

If you find this video useful, like, share and subscribe to support the channel!
► Subscribe: https://www.youtube.com/c/DataDaft?su...


Code used in this Python Code Clip:

nested = [[1,2,3],[4,5,6],[7,8,9]]

Depth 2 flatten with list comprehension
flattened = [num for sublist in nested for num in sublist]

print(flattened)

Depth 2 flatten with for loops
flattened2 = []

for sublist in nested:
for num in sublist:
flattened2.append(num)

print(flattened2)

Flatten with numpy
import numpy as np

np.array(nested).flatten()

Nested lists greater than depth 2
nested3 = [nested, nested]

Flatten depth 3 nested with numpy
import numpy as np

np.array(nested3).flatten()

Add extra sublists as extra loops:
[num for sub1 in nested3 for sub2 in sub1 for num in sub2]

Flatten lists with unequal levels of nesting

unequal_nest = [1 , [2, 3], [[4,5],[6, 7]]]

def flatten_list(x):
for item in x:
if type(item) in [list]:
for num in flatten_list(item):
yield(num)
else:
yield(item)

list(flatten_list(unequal_nest))



Note: YouTube does not allow greater than or less than symbols in the text description, so the code above will not be exactly the same as the code shown in the video! I will use Unicode large < and > symbols in place of the standard sized ones. .


⭐ Kite is a free AI-powered coding assistant that integrates with popular editors and IDEs to give you smart code completions and docs while you’re typing. It is a cool application of machine learning that can also help you code faster! Check it out here: https://www.kite.com/get-kite/?utm_me...


En esta página del sitio puede ver el video en línea How To Flatten Nested Lists in Python de Duración hora minuto segunda en buena calidad , que subió el usuario DataDaft 30 noviembre 2020, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 5,138 veces y le gustó 108 a los espectadores. Disfruta viendo!