home
Learn
screen_rotation
# create a new list using loop mylist = [[10,20,30,40,50],[100,200,300,400,500],[1000,2000,3000,4000,5000]] newlist = [] for innerlist in mylist: for item in innerlist: if item > 200: newlist.append(item) else: newlist.append(item*item) print("using for loop:",newlist) # create a new list using comprehension mylist = [[10,20,30,40,50],[100,200,300,400,500],[1000,2000,3000,4000,5000]] newlist = [item if item > 200 else item*item for innerlist in mylist for item in innerlist ] print("using list comprehension:",newlist)
Program Output
using for loop: [100, 400, 900, 1600, 2500, 10000, 40000, 300, 400, 500, 1000, 2000, 3000, 4000, 5000] using list comprehension: [100, 400, 900, 1600, 2500, 10000, 40000, 300, 400, 500, 1000, 2000, 3000, 4000, 5000]