228k views
3 votes
The aim of this activity is to implement an algorithm that returns the union of elements in a collection. Although working with sets is quick and easy in Python, sometimes we might want to find the union between two lists. Create a function called unite_lists, which uses a loop to go through both lists and return common elements. Do not use the built-in set function.

User Edzillion
by
8.6k points

1 Answer

2 votes

Answer:

The function in Python is as follows:

def unite_lists(A, B):

union = []

for elem in A:

if elem in B:

union.append(elem)

return union

Step-by-step explanation:

This defines the function

def unite_lists(A, B):

This initializes an empty list for the union list

union = []

This iterates through list A

for elem in A:

This checks if the item in list A is in list B

if elem in B:

If it is present, the item is appended to the union list

union.append(elem)

This returns the union of the two lists

return union

User Sujit Singh
by
7.3k points

No related questions found

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.