I need to check whether two lists have any same elements, but these same elements must also be at same index positions.
I came up with a following ugly solution:
def check_any_at_same_index(list_input_1, list_input_2):
# set bool value
check_if_any = 0
for index, element in enumerate(list_input_1):
# check if any elements are the same and also at the same index position
if element == list_input_2[index]:
check_if_any = 1
return check_if_any
if __name__ == "__main__":
list_1 = [1, 2, 4]
list_2 = [2, 4, 1]
list_3 = [1, 3, 5]
# no same elements at same index
print check_any_at_same_index(list_1, list_2)
# has same element 0
print check_any_at_same_index(list_1, list_3)
There must a better a quicker way to do this, any suggestions?
You can use zip() function and a generator expression within any() if you want to check if there are any equal items in same index.
any(i == j for i, j in zip(list_input_1, list_input_2))
If you want to return that item (the first occurrence) you can use next():
next((i for i, j in zip(list_input_1, list_input_2) if i == j), None)
If you want to check the all you can use a simple comparison:
list_input_1 == list_input_2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With