Comparison of 2d lists


I have two 2d lists:

lst1 = [[1,'abc'],

lst2 = [[1,'abc'],

What I want to do is compare them both at [i][0], and if it is the same e.g both lists have 1 at [0][0], I would like to append only the [i][1] of list2(shorter list) to a new list called main list. Else append ‘-1’ because I’d like to keep the length of list1 since its a comparison.

The code I have so far:

mainlst = [i[1][1] if i[0][0]==i[1][0] else -1 for i in zip(lst1,lst2)]


The output I’m having:

['abc', 'abcv', -1]

But the output I want is:

['abc', 'abcv', -1,-1, 'tftg']

Will lst2 always be the shorter list or not necessarily?

Also, if i represents index of the list, then technically, based on what you have described, the resulting list would be ['abc', 'abcv', -1,-1, '-1'] because in lst2, [2][0] is 5 but in lst1, the 5 is located at [4][0].

Is it possible you are just wanting to check if lst1 has a corresponding first dimension value of that is the same as the first dimension value of lst2? If there is one and the second dimension value is the same, then you would add the second dimension value to the final list, otherwise add -1?

1 Like

Thank you for your reply. Your point about index makes sense to me and i understand why it didnt provide the output i wanted. And your assumption about what I’m trying to do is absolutely correct. What should I do instead?

And yes lst2 will always be the shorter one.

That’s because zip() only takes the length of the shortest element.
You either have to make the second list longer to match the first - or use another method entirely.

Plus you approach cannot work given you want to match the [5,'tftg'] element. But how? How is Python supposed to know this element on index 2 in one list is supposed to be compared to another element on index 4?

You only compare items with the same index. But you want to compare items based on the first entry in the nested lists. You’d basically have to search through the entire second list for every item in the first list, in order to find a potential match. This cannot be done with zip().

You could create a dictionary out of lst2 to use as a lookup. Then iterate through the elements of lst1 and check if the second element of each sub list of lst1 (val) is the same as the value for lookup’s key of the same value.

lookup = { elem[0]: elem[1] for elem in lst2 }
result = [ val if val == lookup.get(key) else -1 for (key, val) in lst1 ]

print(result) # ['abc', 'abcv', -1, -1, 'tftg']