-4

I am new to the python. I have two lists:

l1 = [1,1,1]
l2 = [1,1,1]

Now, I have to check whether these two are equal or not. I have a solution which I am currently using:

def comp(l1,l2):
    #condition we are checking [1,1,1] and  [1,1,1]
    try:
        a= set(l1)  #converting a list into set , as set will return the length on basis of unique elements.
        b= set(l2)
        return ((a == b) and (len(a) == 1) and (len(b) == 1))
    except TypeError:
        return False

Now, with this I am able to solve the task. But I am trying to do it elementwise.

l1 = [1,1,12]
l2 = [1,1,1]

Then I can treat the 12 as a 1 so I need to know which number is not matching. Can any one help me with this ?

rajah9
  • 11,645
  • 5
  • 44
  • 57
ganesh kaspate
  • 1
  • 9
  • 41
  • 88
  • 4
    Why are the tags `pandas` and `numpy` here? – Aryerez Nov 11 '19 at 12:34
  • 1
    Lists can be compared with `l1 == l2`, it will, behind the curtains, check if the length is the same, and iterate over the elements. You implementations however, will check if the two lists have the same elements, so `[2,1,1]` and `[1,2]` will be the same in your `comp` function. – Willem Van Onsem Nov 11 '19 at 12:34
  • There is nothing wrong with that. Actually I am trying to equivalent some data so – ganesh kaspate Nov 11 '19 at 12:34
  • 1
    Will the lists always have the same length? – Cleb Nov 11 '19 at 12:35
  • Does this answer your question? [How can I compare two lists in python and return matches](https://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches) – Divyesh patel Nov 11 '19 at 12:36
  • It will be mostly length. either it might be empty or may be 2 elements. but mostly three – ganesh kaspate Nov 11 '19 at 12:36

4 Answers4

3

Assuming they have the same length, you could do:

{i: (v, l2[i]) for i, v in enumerate(l1) if v != l2[i]}

which returns

{2: (12, 1)}

for you example above. The keys are the indices, the values are tuples of the respective values in the lists.

Cleb
  • 25,102
  • 20
  • 116
  • 151
3

If you need to know if the two list are exactly the same you can do l1 == l2 directly.

If you need to compare the lists element-wise (assuming they have the same length) and you only play with list of numbers, you can use numpy arrays :

import numpy as np

l1 = np.array([1,1,12])
l2 = np.array([1,1,1])

l1 == l2 # array([ True, True, False])
Donshel
  • 563
  • 4
  • 13
0

Assuming the lists are always the same length, You can do:

is_all_equel = True
for i in range(len(l1)):
    if l1[i] != l2[i]:
        print("index " + str(i) + " is " + str(l1[i]) + " in list 1, and " + str(l2[i]) + " in list 2")
        is_all_equel = False

In is_all_equel will be the answer if all the elements in the lists are equel

Aryerez
  • 3,417
  • 2
  • 9
  • 17
0

something like:

l1 = [1,1,12]
l2 = [1,1,1]
for elem in l1:
    if not elem in l2:
        print(elem)
        print(l1.index(elem))
g kexxt
  • 121
  • 1
  • 5