Comparing two lists and printing the list in Python

Question:

I have two lists Z1 and Z2. I am comparing these two lists and if at least one sublist of Z1 appears in Z2, I want to print full Z1. I present the current and expected output.

Z1=[[0, 4], [0, 5], [4, 5]]
Z2=[[6, 5], [4, 9], [4, 8], [5, 3], [0,4]]

for i in range(0,len(Z1)):
    if (Z1[i]==Z2[i]):
        print("Z1 =",Z1)

The current output is

(Blank)

The expected output is

Z1=[[0, 4], [0, 5], [4, 5]]
Asked By: rajunarlikar123

||

Answers:

You are not looking over all of Z2 at most you arrive at i=2 so you never arrive at the last item in Z2 which is the one you are looking for (which should be i=4, but len(Z1) < 4).

Just loop over both, brute force solution:

>>> for z1 in Z1:
...     for z2 in Z2:
...             if z1 == z2:
...                     print("Z1 =",Z1)
...                     break
... 
Z1 = [[0, 4], [0, 5], [4, 5]]
Answered By: Nathan McCoy

An rather elegant solution can be using sets and their intersection:

Z1=[[0, 4], [0, 5], [4, 5]]
Z2=[[6, 5], [4, 9], [4, 8], [5, 3], [0,4]]

zs1 = set(map(tuple, Z1))
zs2 = set(map(tuple, Z2))

if (zs1 & zs2):
    print("Z1 =",Z1)
Answered By: Michael Butscher

Sets are faster (see Michael’s answer) but the any() function with a comprehension can check the condition in a simple (albeit naive) way:

if any(z in Z1 for z in Z2): 
    print("Z1 =",Z1) 

You could also benefit from set performance by converting Z1 to a set beforehand. Any() will stop iterating as soon as a match is found so your process will not always convert all Z2 values to tuples (when there is a match).

S1 = set(map(tuple,Z1)) 
if any(tuple(z) in S1 for z in Z2): 
    print("Z1 =",Z1) 

With a set, the disjoint method can perform the same thing as any() but with an inverse condition:

S1 = set(map(tuple,Z1)) 
if not S1.isdisjoint(map(tuple,Z2)): 
    print("Z1 =",Z1) 
Answered By: Alain T.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.