Need Help With Python Development?

Work with our skilled Python developers to accelerate your project and boost its performance.

Hire Python Developers

Support On Demand!

Using list comprehension It’s very easy to convert a two dimensional list into a flat (single dimensional) list.

flat_list = [num for childlist in lists for num in childlist]

Limitations:

  • This is the optimal approach if your parent list has components that can be iterated, such as lists or strings, but it won’t work for non-literals like integers and floats.
  • Another situation where this technique cannot be applied is a list with more than two dimensions.

Solution:

L = [
[1,2,3],
[
 	[4,5,6],
 	[7,8,9],
 	[
 		[10,11,12],
 	 		[13,14,15]
 	]
],
16,17,18
]


def flat_my_list(L: list):
result = []
for element in in L:
      try:
      	iter(element)
           	result.extend(flat_my_list(element))
 	except:
 		result.append(element)
return result


flat_my_list(L)

All of those criteria will be fulfilled by the function flat_my_list.

Related Q&A