user11862294
user11862294

Reputation:

List comparison with different sizes

I have two lists

list1=['a','b','c','d']
list2=['c','d']

I have to compare this list1 and list2

  1. if list1 and list2 are same I should not remove any items and I have to keep the list1 as it is. For example list1=[a,c], list2=[a,c] then list1=[a,c]

  2. If list1 has more elements than list2, I should remove the extra elements from the list1 (as shown in the example), here I need list1=['c']

  3. if list1=['c'] then I should keep the list1 as it is i.e. list1=['c']

How should I do it? I tried:

def is_equal(list1, list2):
    "Check both lists are same or not"
    return sorted(list1) == sorted(list2)

I am getting this error, I am not getting it all the time:

    return sorted(interviewers_name_list) == sorted(interviewers_list)
TypeError: '<' not supported between instances of 'str' and 'NoneType'

Should I use loop to iterate it? Do I have any other easy way to do this list comparison?

Upvotes: 0

Views: 73

Answers (3)

Hades1598
Hades1598

Reputation: 320

List comprehension might be what you are looking for. Here is an implementation which might help you.

list1=['a','b','c','d']
list2=['a','c']

if sorted(list1)==sorted(list2):
    print(list1)
else:
    print([elem for elem in list1 if elem in list2 ])

This should return the output

['a','c']

And if both the lists are the same, it just returns list1

Hope this helps!

Upvotes: 0

Sheri
Sheri

Reputation: 1413

This is what i understand from your explanation if two list are equal then it does nothing and simply returns list1, on the other hand if the elements in the lists are not same then it remove extra elements from list1 and make list1 similar to list2

list1=['a','b','c','d']
list2=['a','c']
def is_equal(list1, list2):
    "Check both lists are same or not"
    return sorted(list1) == sorted(list2)


def compare_list(list1, list2):
    if is_equal(list1, list2):
        return list1
    else:
        return sorted((set(list1) & set(list2)))

print(compare_list(list1, list2))

Output:

['a', 'c']

Upvotes: 0

norok2
norok2

Reputation: 26886

I am assuming that your list would contain only unique elements, or that you are otherwise interested only in unique elements.

If that is the case, you should probably use set(). There, the operation you are describing is the .intersection():

a = {'a', 'b', 'c', 'd'}
b = {'c', 'd'}
print(b.intersection(a))
# {'c', 'd'}

a = {'a', 'b', 'c', 'd'}
b = {'a', 'b', 'c', 'd'}
print(b.intersection(a))
# {'a', 'b', 'c', 'd'}

a = {'c'}
b = {'c', 'd'}
print(b.intersection(a))
# {'c'}

Of course, if you start of from a list you could just convert it to set() via:

a = set([1, 2, 3, 4])
print(a)
# {1, 2, 3, 4}

Also, beware that sets do not have a defined order, so you may need to use sorted() on them (which will convert set to a sorted list).

Upvotes: 1

Related Questions