+ 1

I want to append common elements of two lists into a new list and print all elements of two lists in new list without repetition

l=[1,2,3,4] m=[2,3,4,56,7] z=[] for i in l: if i in m: z.append(m[i]) print(z) the elements 2,3,4 should be present in list z but it does not work . and a new list say y=[] must be created which has all elements of I and y with out repeating the elements

19th Dec 2018, 1:13 PM
Mara
4 ответов
+ 10
Yes Diego Acero is correct. This can also be done as : l=[1,2,3,4] m=[2,3,4,56,7] z=[] for i in l: if i in m: z.append(i) print(z)
19th Dec 2018, 1:37 PM
Nova
Nova - avatar
+ 9
You can try this way : First extract element from list l. Then extract element from list m and then compare the first element of l with all elements of m. Then same with second, third and so on. This may help : l=[1,2,3,4] m=[2,3,4,56,7] z=[] for i in l: for j in m: if i==j: z.append(i) print(z)
19th Dec 2018, 1:20 PM
Nova
Nova - avatar
+ 4
shivaani You almost got it! Try changing line 6 for this: z.append(i)
19th Dec 2018, 1:32 PM
Diego
Diego - avatar
+ 4
l = [1, 2, 3, 4] m = [2, 3, 4, 56, 7] # common elements z = list(set(l) & set(m)) print(z) # [2, 3, 4] # all elements without repetition y = list(set(l) | set(m)) print(y) # [1, 2, 3, 4, 7, 56]
19th Dec 2018, 3:25 PM
Anna
Anna - avatar