List comprehension with any

Viewed 1526

I know that following is list comprehension syntax:

List2 = [item for item in List1 if item=='test']

However for nested list comprehension, the syntax changes to how it would have appeared in a normal program:

List3 = [ y for x in toplevelForLoop for y in x ]

The if loop can appear after the first or 2nd for loop as per logic but the sequence is like how it would be in a normal program.

Is below acceptable? I am trying to check if item in ListB is contained within item in ListA

Code:

for itemA in ListA:

    if any([ itemB in itemA for itemB in ListB ])

Is the above code equivalent to the below?

Code:

if any([ itemB in itemA for itemA in ListA for itemB in ListB ])
1 Answers

List comprehension with multiple fors is equivalent to nested for loops. These two are equivalent:

a = [[1, 2], [3, 4]]

## With comprehension
b = [
    number
    for numbers in a
    for number in numbers
]

## Without comprehension
b = []
for numbers in a:
    for number in numbers:
        b.append(number)

# b = [1, 2, 3, 4]

any will be true if any item in the iterator (doesn't need to be a list) is truthy

assert any([True, False, False]) == True
assert any(['string', '', '']) == True
assert any([1, 0, 0]) == True
assert any([False, False, False]) == False
assert any(['', '', '']) == False
assert any([0, 0, 0]) == False

Your two scenarios are not equivalent. Expanding them a little:

for itemA in ListA:
    if any([ itemB in itemA for itemB in ListB ]):
        print("at least some item from ListB exist in itemA")

This code above would print one line for every item from ListA that contains any element from ListB.

This code below will print only one line if the code above would print at least one line:

if any([ itemB in itemA for itemA in ListA for itemB in ListB ]):
    print("at least some item from ListB exist in at at least one item from ListA")
Related