list append gives None as result [duplicate]

冷暖自知 提交于 2019-12-11 18:59:08

问题


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:


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.


来源:https://stackoverflow.com/questions/26151795/list-append-gives-none-as-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!