Python Forum
Recursive Function - Compare 2 lists, return the elements that don't exist in both
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursive Function - Compare 2 lists, return the elements that don't exist in both
#1
I have to do a RECURSIVE FUNCTION, comparing two lists and returning the elements that they don't have in common.

This is what I have so far:

def compare(list1, list2):
    if list2[0] in list1:
        list1.remove(list2[0])
        return compare(list1[1:], list2[1:])

    return list1  

#Example 
 >>>>compare([2, 3, 4, 5], [2, 3])
 [4, 5]
I can compare if the first element of the list (list[0]) is the same but I am having trouble on how to compare the elements if they are not in the first position...I've tried many options but I'm a begginer in programming and don't really know how to do it. It must be a RECURSIVE FUNCTION, I can't use FOR or WHILE. And is there any way that I can do it without using remove()? Thank you so much
Reply


Messages In This Thread
Recursive Function - Compare 2 lists, return the elements that don't exist in both - by KellyBaptist - Dec-22-2018, 10:39 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  function for extracting data from lists Paulman 9 3,004 Nov-09-2021, 04:00 PM
Last Post: Paulman
  Use of function/return Paulman 6 2,578 Oct-24-2021, 11:07 PM
Last Post: Paulman
  Multiple return from function Grimmar 7 3,752 Mar-22-2021, 09:20 PM
Last Post: Grimmar
  Lambda function not return value mbilalshafiq 4 3,571 Jul-04-2020, 07:47 AM
Last Post: ndc85430
  Child class function of Log return "None" mbilalshafiq 2 2,334 Jun-30-2020, 07:22 PM
Last Post: mbilalshafiq
  Question on "define function"; difference between return and print extricate 10 4,990 Jun-09-2020, 08:56 PM
Last Post: jefsummers
  "Plotting and Computation of Logistic Function by Using Taylor Series with Recursive canatilaa 1 1,910 May-13-2020, 04:01 PM
Last Post: jefsummers
  [split] problem with function return value ops 1 3,508 Apr-13-2020, 01:48 PM
Last Post: buran
  Compare elements of tuples / Find edges between nodes Daniel94 1 1,878 Apr-06-2020, 03:32 PM
Last Post: deanhystad
  Function to return today's month, day, and year sbabu 9 5,173 Jan-28-2020, 06:20 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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