Turan Kılıç

Posted on

# Turning Complex Lists into Flatten Lists in Python Without Using Any Libraries

Hello there Turan here, today I'm going to share a algorithm that turns complex lists into simple lists (flatten lists).

First of all, what is a complex list? It is a list that contains different type lists inside it, looks so complex and make it hard to read. For example:

``````l = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
``````

The above list is an example of complex list, we are going to turn it into this:

``````[1, 'a', 'cat', 2, 3, 'dog', 4, 5]
``````

Let me show you the code and explain it to you ^^

``````from typing import List

l = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
flat_list2 = []

def lookInside(l):                  # Takes the list type element
for x in l:                     # For each sub-element of it
if type(x) is not list:     # If the sub-element is not list,
flat_list2.append(x)    # Then add it to flat_list
else:
lookInside(x)           # Else, look inside of it again

# WE ARE STARTING HERE !!!
def makeFlat(l):                    # Getting the list
for e in l:                     # Checking the elements of the list
if type(e) is list:         # If element's type is list then
lookInside(e)           # send that element to lookInside function
else:
flat_list2.append(e)    # Else, (if it is not list) append it to our new flat_list

makeFlat(l)                         # Function call, the complex list has been given to function
print(flat_list2)                   # Printing the flatten list
``````

With the code above, we can turn complex lists into simple (flatten) lists, whatever complex list contains 2nd, 3rd, 4th... degree lists. It doesn't matter for us because we are using recursive function that makes everything easier.

Here how our recursive function works:

1. [ 1, [2], [[3]] ] ==> Our function takes 1 as a normal element

2. [ [2], [[3]] ] ==> Then for [2] we are going to our recursive function, this function looks inside of it then sees that "2" is not list, then add it to new list

3. [ [[3]] ] ==> Then for [[3]] we are going to our recursive function, function looks at it and says that [3] is a list then send it to itself again just as [3]. After that (like [2]) it looks inside of [3] and sees that 3 is not list then add it into new list.

This goes like that :)

I hope it was easy to understand for you, and i hope it helped. Thanks for reading, please leave a like and comment if you want ^^

@Publisher : https://dev.to/toour

John P. Rouillard

What's the purpose of lookInside? Just call makeFlat recursively.

Turan Kılıç

Wow that's a great built-in function. I didn't know that Ruby has this kind of thing. Python just trying to make the job harder :P
Thanks for info, i really preciated! ^^