user3402719 user3402719 - 1 year ago 101
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:
del list_of_numbers1[i]
del list_of_numbers2[i]
return union_list
z = reunion(x,y)

Answer Source

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:

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:

However, I would do it like this

return [number for number in list_of_numbers1 if number in list_of_numbers2]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download