+

Python | Ways to align a 2D list

Method # 1: Using `chain.iterable()`

` `

 ` # Python code for demo ` ` # convert 2nd list to 1st list ` ` # using chain.from_iterables `   ` # import chain ` ` from ` ` itertools ` ` import ` ` chain `   ` ini_list ` ` = ` ` [[` ` 1 ` `, ` ` 2 ` `, ` ` 3 ` `], ` ` [` ` 3 ` `, ` ` 6 ` `, ` ` 7 ` `], ` ` [` ` 7 ` `, ` ` 5 ` `, ` ` 4 ` `]] `   ` # print start list ` ` print ` ` (` ` "initial list" ` `, ` ` str ` ` (ini_list)) `   ` # convert 2d list to 1d ` ` # using chain.from_iterables ` ` flatten_list ` ` = ` ` list ` ` (chain.from_iterable (ini_list)) `   ` # flatten_list print ` ` print ` ` (` ` "final_result" ` `, ` ` str ` ` (flatten_list)) `

` ` Exit:

` initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]] final_result [1, 2, 3 , 3, 6, 7, 7, 5, 4] `

Method # 2: Using List Comprehension

 ` # Python code for demo ` ` # convert 2nd list to 1st list ` ` # using comprehension list ` ` `  ` # import chain ` ` from ` ` itertools ` ` import ` ` chain ` ` `  ` ini_list ` ` = ` ` [[` ` 1 ` `, ` ` 2 ` `, ` ` 3 ` `], ` `  [ 3 , 6 , 7 ], `` `` [ 7 , 5 , 4 < code class = "plain">]] `   ` # print starting list ` ` print ` ` (` ` "initial list" ` `, ` ` str ` ` (ini_list)) `   ` # convert 2d list to 1d ` ` # use list of comprehension ` ` flatten_list ` ` = ` ` [j ` ` for ` ` sub ` ` in ` ` ini_list ` ` for ` ` j ` ` in ` ` sub] ` ` `  ` # print flatten_ list ` ` print ` ` (` ` "final_result" ` `, ` ` str ` ` (flatten_list)) `

Exit:

` initial list [[1, 2, 3], [ 3, 6, 7], [7, 5, 4]] final_result [1, 2, 3, 3, 6, 7, 7, 5, 4] `

Method # 3: Using `functools.reduce`

` `

` # Python code for demonstration # convert 2nd list to 1st list # using functools.reduce   # import functools from functools import reduce    ini_list = [[ 1 , 2 , 3 ], [ 3 , 6 , 7 ], [ 7 , 5 , 4 ]]   # print starting list print ( " initial list " , str (ini_list))   # conversion 2d list in 1d # using functools.reduce flatten_list = reduce ( lambda z, y: z + y, ini_list)   # flatten_list print print ( "final_result" , str (flatten_list)) `

` ` Exit: < / b>

` initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]] final_result [1, 2, 3, 3, 6, 7 , 7, 5, 4] `