Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing same index in 2 lists

I don't have a code for this because I have no idea how to do it, and couldn't find much help on Google.

Is there a way to find if the same indexes on 2 lists are the same?

For example:

x_list = [1, 2, 3, 4, 5]
y_list = [1, 2, A, B, 5]

I want to know whether the first index of X is the same as the first index of Y, the second index of X is the same as the second index of Y, etc. I could do it like:

x_list[0] == y_list[0]

But need an infinite solution.

like image 316
Adam Burros Avatar asked May 28 '26 18:05

Adam Burros


1 Answers

zip the lists and return the test (which returns a boolean as outcome):

[i == j for i, j in zip(x_list, y_list)]

You could use any to quickly check for the existence of a False (means the items are not the same) if you don't need the values:

any(i != j for i, j in zip(x_list, y_list))

The any version would break once a False is found meaning you may not have to traverse the whole lists except in the worst case.

like image 123
Moses Koledoye Avatar answered May 30 '26 08:05

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!