Search code examples
pythonlistcompare

check if element is in anywhere the list


I have two lists:

expected = ["apple", "banana", "pear"]
actual = ["banana_yellow", "apple", "pear_green"]

I'm trying to assert that expected = actual. Even though the color is added at the end to some elements, it should still return true.

Things I tried:

for i in expected:
   assert i in actual

I was hoping something like this would work but it's trying to match the first element apple to banana and returns false rather than checking the entire list and returns true if there is apple anywhere in the list. I was hoping someone can help?

Edit: The lists can be different lengths.


Solution

  • expected = ["apple", "banana", "pear"]
    actual = ["banana_yellow", "apple", "pear_green", 'orange']
    
    for act in actual:
        if not act.startswith(tuple(expected)):
            print(act)
    >>>
    orange
    

    If you want it to work in the opposite way,

    expected = ["apple", "banana", "pear", 'grapes']
    actual = ["banana_yellow", "apple", "pear_green", 'orange']
    expected_ = set(expected)
    for act in actual:
        for exp in expected:
            if act.startswith(exp):
                expected_.discard(exp)
                break
    assert not(expected_), f"{expected_} are not found in actual and " + f"{set(expected)-expected_} are found in actual"
    >>>
    AssertionError: {'grapes'} are not found in actual and {'apple', 'pear', 'banana'} are found in actual
    

    Another way,

    expected = ["apple", "banana", "pear", 'grapes']
    actual = ["banana_yellow", "apple", "pear_green", 'orange']
    for exp in expected:
        assert [exp for act in actual if act.startswith(exp)], f'{exp} not found'
    >>>
    AssertionError: grapes not found