Write a python program to print flatten a nested list

Write a python program to print flatten a nested list

Program
def myfun():
    
    list1 = [[1, 2, 3,4],[ 5, 6, 7, 8]]
    newlist = []
    for x in list1:
        for y in x:
            newlist.append(y)

    print(newlist)
    
if __name__=="__main__":
    myfun()


Output:

[1, 2, 3, 4, 5, 6, 7, 8]


Using itertools
import itertools
def myfun():
    
    list1 = [[1, 2, 3, 4],[ 5, 6, 7, 8]]
    list2 = list(itertools.chain.from_iterable(list1))
    print(list2)
    
if __name__=="__main__":
    myfun()


Output:

[1, 2, 3, 4, 5, 6, 7, 8]


Using list comprehension
def myfun():
    
    list1 = [[1, 2, 3,4],[ 5, 6, 7, 8]]
    list2= [x for y in list1 for x in y]
    print(list2)
    
if __name__=="__main__":
    myfun()



Output:

[1, 2, 3, 4, 5, 6, 7, 8]



More Questions


34 . Write a python program to print flatten a nested list
35 . Write a python program to Find the index of the largest number in the list
36 . Write a python program to Find the index of the smallest number in the list
37 . Write a python program to find absolute value of a number in the list
38 . Write a python program to adding a thousand separator
39 . Write a python program startswith and Endswith Methods
40 . Write a python program to print Nlargest numbers
41 . Write a python program to print Nsmallest numbers
42 . Write a python program to check two strings are Anagram or not
43 . Write a python program to checking internet speed
44 . Write a python program to print reserved keywords



For latest job updates join Telegram Channel: https://t.me/sateeshm