Hi I need a single list of nested lists in python without any inbuilt function. I did a lot of research but not able to find without flatten or ravel function().
for ex:
input = [1,2,[2,3,[4,5]],[6,7],[8,[9]],10]
output = [1,2,2,3,4,5,6,7,8,9,10]
Hi I need a single list of nested lists in python without any inbuilt function. I did a lot of research but not able to find without flatten or ravel function().
for ex:
input = [1,2,[2,3,[4,5]],[6,7],[8,[9]],10]
output = [1,2,2,3,4,5,6,7,8,9,10]
You can use recursion to implement your own flatten function. Here's a nice tutorial explaining the concepts of recursion.
The idea here is that you loop through each element in your list and if you encounter a sublist you recursively call the same method with the current list. If it's a valid element you add it to to your output list.
Example:
def flatten(input_list, output_list=[]):
for i in input_list:
if isinstance(i, list):
flatten(i, output_list)
else:
output_list.append(i)
return output_list
input_list = [1,2,[2,3,[4,5]],[6,7],[8,[9]],10]
print(flatten(input_list))
Outputs:
[1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I found a solution on my own. Below is the solution:
c = []
def test(a):
for val in a:
if type(val) == list:
test(val)
else:
c.append(val)
return c
a=[1,2,[2,3,[4,5]],[6,7],[8,[9]],10] print test(a)