94,937 views
0 votes
0 votes
Write a function list_intersection that takes two lists as parameters. Return a list that gives the intersection of the two lists- ie, a list of elements that are common to both lists. Run the following test cases and make sure your results are the same (the ordering of your outputs does not matter - [3,2] is the same as [2,3]):

User Iakobski
by
2.9k points

2 Answers

6 votes
6 votes

Answer:

def list_intersection(list1, list2):

intersected_list = [number for number in list1 if number in list2]

return intersected_list

list1 = [11, 5, 676, 0, 42, 32]

list2 = [0, 89, 211, 11]

print(list_intersection(list1, list2))

Step-by-step explanation:

- Inside the function, create a new list called intersected_list to check if any number in list1 is also in the list2. If a match is found put the number in the intersected_list. * Take a look how Python enables us to do this with just one line of code

- Then create two lists to compare

- Call the function and print the result

User Pez Cuckow
by
3.0k points
3 votes
3 votes

Answer:

  1. def list_intersection(l1, l2):
  2. inter_list = []
  3. for x in l1:
  4. for y in l2:
  5. if(y == x):
  6. if(x not in inter_list):
  7. inter_list.append(x)
  8. return inter_list
  9. list1 = [3, 5, 5, 7, 7, 10]
  10. list2 = [4, 6, 7, 7, 8, 8, 10]
  11. print(list_intersection(list1, list2))

Step-by-step explanation:

The solution code is written in Python.

Firstly, create a function list_intersection that takes two input lists, l1 and l2 (Line 1). Next, create a new list, inter_list, to hold the intersect numbers from the two input lists (Line 2).

Create a two-layer for loop to traverse through every number in l1 and compare it with every number in l2 (Line 4 - 5). If any one of the numbers from l2 is equal to the current number from L1, add this common number to inter_list (Line 8). This is important to check the current common number is not in the inter_list (Line 7) to avoid number duplication.

We can test the function using the two sample lists (Line 12 -13) and print the result (Line 14). We shall get the output [7, 10].

User Marneylc
by
2.9k points