list append gives None as result [duplicate]

2019-09-15 17:44发布

This question already has an answer here:

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

1条回答
甜甜的少女心
2楼-- · 2019-09-15 18:36

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.
查看更多
登录 后发表回答