0

i just wrote a function that should print out all the values 2 dictionaries have in common. so if use the following line in my function:

print list_intersection([1, 3, 5], [5, 3, 1])       

The output should be:

[1, 3, 5]

I wrote the following code to solve this problem:

def list_intersection(list_1, list_2):
    empty_list = []
    for number in list_1:
        if number in list_2:
            return empty_list.append(number)

The problem is that i only get None as output, but if i use the following code:

def list_intersection(list_1, list_2):
    empty_list = []
    for number in list_1:
        if number in list_2:
           return number

I get the numbers printed out one by one that are in both lists. I have no idea why my program isn't just putting the numbers both lists have in common into my empty_list and return me my empty_list

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223

1 Answers1

1

I suppose the assertion could be made that this isn't exactly a duplicate. For the reason why .append() returns None please see Alex Martelli's erudite answer.

For your code instead do:

def list_intersection(list_1, list_2):
    intersection = []
    for number in list_1:
        if number in list_2:
            intersection.append(number)
    return intersection

This avoids the following pitfalls:

  1. Returning None instead of the list intersection.
  2. Returning None for each element of list_2.
Community
  • 1
  • 1
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223