Q. Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python using at least one list comprehension. Run the complete program and show output.
Answer :-
lst1 = eval(input("Enter first list: " )) lst2 = eval(input("Enter second list: ")) l = [i for i in lst1 if i in lst2 ] for i in l : while l.count(i) > 1: # Note without duplicate l.remove(i ) print(l)
Direct Method :-
lst1 = eval(input("Enter first list :-")) lst2 = eval(input("Enter second list :-")) lst = [ ] for i in lst1 : if i in lst2 : lst.append( i ) for i in lst : if lst.count( i ) > 1 : lst.remove( i ) print("Comman elements are :-", lst)
Output :-
Enter first list: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Enter second list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[1, 2, 3, 5, 8, 13]
>>>
Enter second list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[1, 2, 3, 5, 8, 13]
>>>
Enter first list: [8,7,4,6,9,3,2,1,4,5,8,6]
Enter second list: [7,8,1,4,2,9,6]
[7, 9, 2, 1, 4, 8, 6]
>>>
Enter second list: [7,8,1,4,2,9,6]
[7, 9, 2, 1, 4, 8, 6]
>>>
lst1 = eval(input("Enter first list: " ))
ReplyDeletelst2 = eval(input("Enter second list: "))
l = [i for i in lst1 if i in lst2 ]
for i in l :
while l.count(i) > 1: # Note without duplicate
l.remove(i )
print(l)
Right : )
DeleteDon't forget to indent properly after the for loop
ReplyDeleteYes.
DeleteYou can also write this instead of that
ReplyDeletelst=[a[i] for i in range(len(a)) if a[i] in b and a[i] not in a[i+1:] ]
Yes.
DeleteThis comment has been removed by the author.
DeletePost a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )