I believe that in this case your code could be optimised as:
Sometimes its not applicable (when you need to preserve order of elements or elements of your list cant be stored in a set). If you need to iterate over list, dont use
Or you could just swap your variables and use same code to compare them:
Ruilen = list(set(RuilenNaar) & set(RuilenVanaf))Converting lists to sets to do some operation like union, intersection or set difference is quite common practice in python.
Sometimes its not applicable (when you need to preserve order of elements or elements of your list cant be stored in a set). If you need to iterate over list, dont use
for i in range(len(my_list))
, but iterate directly over that list, for more read Never use for i in range... Your code on lines 7-16 and 18-27 is basically same - that suggests that perhaps using some function that accept two lists could be a good idea, after that you can use:if len(list_a) > len(list_b): list_c = func(list_a, list_b) # func is function that accepts two lists as arguments else: list_c = func(list_b, list_a)without repeating same code.
Or you could just swap your variables and use same code to compare them:
if len(list_a) > len(list_b): list_a, list_b = list_b, list_a # if list_a is longer than list_b, swap them for item in list_a: # code that suppose that len(list_a) <= len(list_b) - now it is do stuff ...Actually your code would work regardless of iteration over longer or shorter list, so you could remove "half" of it.