user3402719 user3402719 - 1 month ago 9
Python Question

python program returns empty list

I've recently took up Python programming and I've written a simple function that takes two lists and returns a new one that does a reunion of the two lists. However when I run the code it returns an empty list. Please help:

x = [1, 2, 3]
y = [4, 5, 6]


def reunion(list_of_numbers1,list_of_numbers2):
union_list = list()
for i in range(0,len(list_of_numbers1)):
if list_of_numbers1[i] in list_of_numbers2 is True:
union_list.append(i)
del list_of_numbers1[i]
del list_of_numbers2[i]
return union_list
z = reunion(x,y)
print(z)

Answer

In your example it should return you an empty list, as there are no common numbers.

You want to do:

for number in list_of_numbers1:
    if number in list_of_numbers2:
        union_list.append(number)

This may add duplicates. To avoid those,

for number in list_of_numbers1:
    if number in list_of_numbers2 and number not in union_list:
        union_list.append(number)

However, I would do it like this

return [number for number in list_of_numbers1 if number in list_of_numbers2]
Comments