Python | Convert Triple nesting to Double nesting list

Sometimes, while working with lists, we can have a problem in which we need to perform the flattening of nested list. This kind of problem have been discussed many times. But sometimes, flattening can be from a triple to double nesting as well. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension
This task can be performed using technique of list comprehension. In this, one can just take the initial element of triple nested list and just unpack it to double nested list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert Triple nesting to Double nesting list
# using list comprehension
  
# initialize list
test_list = [[[1, 4, 6]], [[8, 9, 10, 7]]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Triple nesting to Double nesting list
# using list comprehension
res = [sub[0] for sub in test_list]
  
# printing result
print("Double nested list from triple nested : " + str(res))

chevron_right


Output :



The original list is : [[[1, 4, 6]], [[8, 9, 10, 7]]]
Double nested list from triple nested : [[1, 4, 6], [8, 9, 10, 7]]

 

Method #2 : Using chain.from_iterable()
This task can also be performed using this function. This is the inbuilt method that is made to perform the task of flattening a list and hence is highly recommended to perform this task.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert Triple nesting to Double nesting list
# using chain.from_iterable()
from itertools import chain
  
# initialize list
test_list = [[[1, 4, 6]], [[8, 9, 10, 7]]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Triple nesting to Double nesting list
# using list comprehension
res = list(chain.from_iterable(test_list))
  
# printing result
print("Double nested list from triple nested : " + str(res))

chevron_right


Output :

The original list is : [[[1, 4, 6]], [[8, 9, 10, 7]]]
Double nested list from triple nested : [[1, 4, 6], [8, 9, 10, 7]]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.