Python Forum
Thread Rating:
  • 2 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Comparing 2 lists
#2
I believe that in this case your code could be optimised as:
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.
Reply


Messages In This Thread
Comparing 2 lists - by BerryK - Apr-13-2017, 04:28 PM
RE: Comparing 2 lists - by zivoni - Apr-13-2017, 05:09 PM
RE: Comparing 2 lists - by snippsat - Apr-13-2017, 05:52 PM
RE: Comparing 2 lists - by BerryK - Apr-14-2017, 11:42 AM
RE: Comparing 2 lists - by volcano63 - Apr-15-2017, 09:46 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  comparing two lists Siylo 19 9,983 Jan-23-2019, 02:09 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020