Python looping through specific element in list

Question:

I have two lists in following manner and I am trying to compare them in some specific style:

a = [[18, 299, 559], [18, 323, 564], [18, 353, 564], [18, 391, 570], [18, 448, 570]]

b = [[18, 353, 564], [18, 299, 559], [18, 323, 564], [18, 391, 570], [18, 448, 570]]

What I want

I want to compare every element of a with b in following order.

For instance, in above case after first element [18, 299, 559] of a equals [18, 299, 559] of b, the loop will break and in the new loop 2nd element of a i.e [18, 323, 564] will be compared from [18, 323, 564] of b and onwards.

The point here is that new loop should not start again iterating from first element of bwhile comparing all elements of a individually with all of b from 0th index.

P.S. In this example I am not trying to check the existence of elements in both lists, or finding any missing elements which can be easily done by using set method. This logic is just for my own knowledge

What I tried

All ordinary nested loop methods like below:

for i in a:
    for j in b: #after break it would always start with first element in b
        if i == j:
            break

the problem here is after every break new i is compared from first element of b and not from last element which was matched with a

Something which is going through my mind looks like this:

for i in a:
    for j in b: 
        if i == j:
           print something
           save index of j 
           break

        in the next loop start comparing new i from this saved index of j                        

yet, I am not able to put this idea into code though.

I know this sounds absurd but can something like this be implemented in python as far as looping is concern? All ideas and hints are welcomed.

Asked By: Dhruvsito

||

Answers:

Sure, you could just trace how far you’ve come in b. I’ll call this variable start_j, from there on it is allowed to start comparing in b:

a = [[18, 299, 559], [18, 323, 564], [18, 353, 564], [18, 391, 570], [18, 448, 570]]
b = [[18, 353, 564], [18, 299, 559], [18, 323, 564], [18, 391, 570], [18, 448, 570]]

start_j = 0

for i in range(len(a)):
    for j in range(start_j, len(b)):
        if a[i] == b[j]:
            print 'match found:', i, j
            start_j = j
            break

If matching elements have been found, start_j is set to the newest j and the next time the inner loop (for checking elements in b) starts there.

Output:

match found: 0 1
match found: 1 2
match found: 3 3
match found: 4 4
Answered By: adrianus

From your description:

P.S. In this example I am not trying to check the existence of elements in both lists, or finding any missing elements which can be easily done by using set method. This logic is just for my own knowledge

I think you are trying to do a set comparison between the two lists. Why not turning them into sets?

aset = set(tuple(item) for item in a)
bset = set(tuple(item) for item in b)

print 'Items only in A:', aset - bset
print 'Items only in B:', bset - aset
print 'Items in common:', aset & bset

Note: I have to turn each sub-list into a tuple since a list is not hashable, thus cannot be in a set.

Answered By: Hai Vu

How about this:

start_idx = 0
for i in a:
    for j_idx, j in enumerate(b[start_idx:], start=start_idx):
        if j==a:
            print 'Bingo!'
            start_idx = j_idx
            break

P.S range(len(a)) – it’s ugly 🙂

Answered By: El Ruso

Here’s how to do it without continue or beak…

a = [[18, 299, 559], [18, 323, 564], [18, 353, 564], [18, 391, 570], [18, 448, 570]]

b = [[18, 353, 564], [18, 299, 559], [18, 323, 564], [18, 391, 570], [18, 448, 570]]

matches = []

for i in xrange(len(a)):
    for j in xrange(len(b)):
        if a[i] == b[j]:
            matches.append([i,j])

for match in matches: print(match)
Answered By: Aaron

If both of your lists have the same element or you don’t know this might be a efficient yet not elegant solution. (I agree the range(len(a)) is ugly)

a = [[18, 299, 559], [18, 323, 564], [18, 353, 564], [18, 391, 570], [18, 448, 570]]

b = [[18, 353, 564], [18, 299, 559], [18, 323, 564], [18, 391, 570], [18, 448, 570]]

# You will compare the length of the list that is the shortest and use that length to iterate over the elements
if (len(a) <= len (b)):
    index_same_elements = []
    len_lists = len(a)
    for i in range(len_lists):
        if a[i]==b[i]:
            print(f'For the index {i}, element in a is equal to the element in b')
            index_same_elements.append(i)

else:
    index_same_elements = []
    len_lists = len(b)
    for i in range(len_lists):
        if a[i]==b[i]:
            print(f'For the index {i}, element in a is equal to the element in b')
            index_same_elements.append(i) 

The index_same_elements will allow you to identify which elements are the same in both lists. Hope it helps someone reading this 7 years after lol

Answered By: br1_ram
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.