Check if list is equal

Asked

Viewed 787 times

8

I have the following list:

x = [([1,2], [1, 2]), ([1,2], [4, 5])]

And I wanted to check if the first list of each Tuple is always the same.

Note: the list x contains tuples with lists. These tuples may vary, meaning there may be more tuples with other values.

1 answer

7


I would use the method all() Python doing a for in tuples.

Example:

a = [([1, 2], [1, 2]), ([1, 2], [4, 5])] # primeira lista igual
b = [([1, 2], [1, 2]), ([1, 3], [4, 5])] # primeira lista diferente
c = [([1, 2], [2, 2]), ([1, 2], [4, 5]), ([1, 2], [4, 2]), ([1, 2], [1, 6]), ([1, 2], [6, 3])]
d = [([1, 2, 3, 4], [2, 2]), ([1, 2, 3, 4], [4, 5]), ([1, 2, 3, 4], [4, 2]), ([1, 2, 3, 4], [1, 6]), ([1, 2, 3, 4], [6, 3])]

all([y == x[0] for y in [x[0] for x in a]])
True

all([y == x[0] for y in [x[0] for x in b]])
False

all([y == x[0] for y in [x[0] for x in c]])
True

all([y == x[0] for y in [x[0] for x in d]])
True
  • what if the list has more tuples?? because the number of tuples is undetermined..

  • @Stinrose doesn’t matter how many items are on the first list, or how many lists are on the tuple. The answer is updated with more examples.

  • but in this case I will not have 2 lists to compare whether they are different or not... I in the code have a function in which I ask for this list, and I need to test if what they have given me is in accordance with the request... in this case it has to have the first list of each always equal

  • This is exactly what this code does. It takes all the first lists of tuples and checks if they are equal. If any is not equal it returns False

  • ah, you’re right! thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.