When I use one-line-for loop in Python, I will got two different values depending on the process I choose(Assign and append processes). I want to understand the difference and how they work. In the following two examples, I trying to write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
First program with append and I get the right result:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
def common_in_two_lists(list1, list2):
re_list = []
[re_list.append(val1) for val1 in list1 for val2 in list2 if val1==val2 and val1 not in re_list]
return re_list
After call the function and print output list:
l = common_in_two_lists(a, b)
print(l)
and the output is:
[1, 2, 3, 5, 8, 13]
But when I use assign way as the following I will got the wrong answer:
def common_in_two_lists(list1, list2):
re_list = []
re_list = [val1 for val1 in list1 for val2 in list2 if val1==val2 and val1 not in re_list]
return re_list
l = common_in_two_lists(a, b)
print(l)
and the output is:
[1, 1, 2, 3, 5, 8, 13]
Anyone can learn me to understand How do this two different way work?