Home > Back-end >  how do i compare 2 different string lists and return the difference if one is bigger?
how do i compare 2 different string lists and return the difference if one is bigger?

Time:12-20

please help me subtract the existing string from the list VideoList so we have a difference and should be formatted into a new list

Database = ["vill du ha","garry", "yao"]  #this is the list of the local data we have 
VideoList = ["garry", "vill du ha", "yao", "potato"] #this list has the same data as Database or more

#My code:
if len(VideoList) == len(Database):
    print("No new videos")
else:
 new_List = #i don't know what to do here but i want the list VideoLise to subtract the existing string in Data base and return what's left from VideoList as a List so the output should be NewList = ["potato"]

CodePudding user response:

You can convert both lists to sets and use the set difference operator:

diff = set(VideoList) - set(Database)
if diff:
    new_list = list(diff)
    print(new_list)
else:
    print("No new videos")

Output:

['potato']

CodePudding user response:

instead of else you can do: elif len(VideoList) > len(Database): print(f"you have {len(VideoList) - len(Database)} new videos")

CodePudding user response:

You can check whether the element of VideoList is present in Database or not like

Database = ["vill du ha","garry", "yao"]
VideoList = ["garry", "vill du ha", "yao", "potato"] 

if len(VideoList) == len(Database):
    print("No new videos")
else:
    new_list=[]
    for element in VideoList:
        if not element in Database:
            new_list.append(element)

CodePudding user response:

This is a good case for using the set operator 'difference'. Convert your lists to sets, get the difference, and then convert the result back to a list:

>>> Database = ["vill du ha","garry", "yao"]
>>> VideoList = ["garry", "vill du ha", "yao", "potato"]
>>> new_list = list(set(VideoList).difference(set(Database)))
>>> new_list
['potato']
  • Related