May 30, 2011

Using set to determin the difference between two lists

in a previous bit of code i offered a suggestion to use [-1] to find the latest created textfile object in blender, this works fine if you don't have existing textfiles with names that are alphabetically 'higher' than the default 'Text' name. When this is the case, and you add a new textfile data object you might consider doing something like:
  • first store the old list of textnames (text_names)
  • create the textfile
  • store the new list of textnames (text_names2)
  • run get_latest_lext(text_names, text_names2) over them, it will return the 'difference', being the newly created file.
def get_latest_text(list1, list2):
    return set(list2)-set(list1)

text_names = ["Text", "Text.001", "Text.002", "Text.003", "Ukraine"]
text_names2 = ["Text", "Text.001", "Text.002", "Text.003", "Text.004", "Ukraine"]

print(get_latest_text(text_names, text_names2))
# >>> "Text.004"