M.Sc Python Programming Assignment 6

M.Sc Python Programming Assignments

Assignment 6

Question:

 

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.

Code:

				
					def find_common_elements(list1, list2):
    common_elements = []

    for element in list1:
        if element in list2 and element not in common_elements:
            common_elements.append(element)

    return common_elements

# Example lists
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]

common_elements = find_common_elements(list1, list2)

print("Common elements:")
print(common_elements)

				
			

Output:

				
					Common elements:
[4, 5, 6]

				
			
Tech Amplifier Final Logo