Reputation: 41961
I have several long lists in python and have compare them and find the lists that are equal to each other except the last elements in the them. Which is the fastest way?
Upvotes: 9
Views: 18164
Reputation: 7338
# choose n to be whatever "last few elements" you want
n = 5
if list1[:-n] == list2[:-n]:
print("The lists are the same")
Using the variable n
lets you exclude any number of last "elements" from the lists.
Upvotes: 0
Reputation: 31
To compare two lists, I think something like this would avoid copying any part of your lists, and stops as soon as a mismatch is found:
len(a)==len(b) and all(a[i] == b[i] for i in range(len(a)-1))
To find all matches in an arbitrary set of lists, I think you'd need to compare each pair of lists -- or at least, each pair which you haven't checked some equivalent version of (e.g., if A=B and B=C, you don't need to check A=C). I don't know offhand of an algorithm that makes this simple.
Alternatively, if the lists are outrageously long and you want to avoid traversing them, you could maybe compute a checksum of the first N-1 elements of each, and then just compare the checksums.
Upvotes: 1