How to compare two strings in a list in python

Use set intersection for this:

list[set[listA] & set[listB]]

gives:

['a', 'c']

Note that since we are dealing with sets this may not preserve order:

' '.join[list[set[john.split[]] & set[mary.split[]]]]
'I and love yellow'

using join[] to convert the resulting list into a string.

--

For your example/comment below, this will preserve order [inspired by comment from @DSM]

' '.join[[j for j, m in zip[john.split[], mary.split[]] if j==m]]
'I love yellow and'

For a case where the list aren't the same length, with the result as specified in the comment below:

aa = ['a', 'b', 'c']
bb = ['c', 'b', 'd', 'a']

[a for a, b in zip[aa, bb] if a==b]
['b']

  • Unknown.PY
  • January 27, 2022

This tutorial will discuss comparing two lists of strings in python.

However, at the end of this article, you'll learn the Simplest way to:

  • Check if the two lists are similar
  • Get the duplicated item in two lists
  • Get the unique items in two lists

Check if the two lists are similar

To check if the two lists are similar, use the == operator.

If both lists are similar, it returns True. Otherwise, it returns False.

Example:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Check if both lists are similar
print[list_1 == list_2]

Output:

False

Let's see how to use it with the if statement:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Check if both lists are similar
if list_1 == list_2:
    print[True]
else:
    print[False]

Output:

Advertisements
False

Get the duplicated item of two lists

There are many ways to get duplicated items in two lists, but we'll focus on the simple way in the following example.

 Let's see an example:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Duplicated Items
duplicated = [i for i in list_1 if i in list_2]

# Output
print[duplicated]

Output:

[c]

How the program works:

  1. Iterate over list_1
  2. Check if list_1's items exist on list_2
  3. Append to a new list if so

If the above example is hard to understand, we can use the standard syntax:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

new_list = []
# Iterate Over list_1
for i in list_1:
    # Check if item exist on list_2
    if i in list_2:
        # Append to new_list
        new_list.append[i]

# Print new_list
print[new_list]

Output:

['c']

Get the unique items of two lists

Unique items mean items that are not duplicated in both lists.

We'll use the same method as the duplicated example to get the unique items.

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Get the unique items
unique = [i for i in list_1 if i not in list_2]

# Output
print[unique]

Output:

['a', 'b']

We've used not in operator to check if list_1's items do not exist in list_2.
For more information about python operators, I recommend you visit Python Operators.

We can also use the set[] function to get unique items.

Example:

# Lists
list_1 = ['a', 'b', 'c']
list_2 = ['q', 's', 'c']

# Get the unique items
unique = set[list_1] - set[list_2]

# Output
print[unique]

Output:

{'a', 'b'}

As you can see, we got the result as a set. To convert Set to List, follow the example below.

# Convert to list
print[list[unique]]

Output:

['b', 'a']

In this article, we will understand the different ways to compare two lists in Python. We often come across situations wherein we need to compare the values of the data items stored in any structure say list, tuple, string, etc.

Comparison is the method of checking the data items of a list against equality with the data items of another list.

Methods to Compare Two Lists in Python

We can use either of the following methods to perform our comparison:

  • The reduce[] and map[] function
  • The collection.counter[] function
  • Python sort[] function along with == operator
  • Python set[] function along with == operator
  • The difference[] function

1. Python reduce[] and map[] functions

We can use the Python map[] function along with functools.reduce[] function to compare the data items of two lists.

The map[] method accepts a function and an iterable such as list, tuple, string, etc. as arguments.

It applies the passed function to each item of the iterable and then returns a map object i.e. an iterator as the result.

The functools.reduce[] method applies the passed function to every element of the input iterable in a recursive manner.

Initially, it would apply the function on the first and the second element and returns the result. The same process will continue on each of the elements until the list has no elements left.

As a combination, the map[] function would apply the input function to every element and the reduce[] function will make sure that it applies the function in a consecutive manner.

Example:

import functools 


l1 = [10, 20, 30, 40, 50] 
l2 = [10, 20, 30, 50, 40, 70] 
l3 = [10, 20, 30, 40, 50] 

if functools.reduce[lambda x, y : x and y, map[lambda p, q: p == q,l1,l2], True]: 
    print ["The lists l1 and l2 are the same"] 
else: 
    print ["The lists l1 and l2 are not the same"] 

if functools.reduce[lambda x, y : x and y, map[lambda p, q: p == q,l1,l3], True]: 
    print ["The lists l1 and l3 are the same"] 
else: 
    print ["The lists l1 and l3 are not the same"] 

Output:

The lists l1 and l2 are not the same
The lists l1 and l3 are the same

2. Python collection.counter[] method

The collection.counter[] method can be used to compare lists efficiently. The counter[] function counts the frequency of the items in a list and stores the data as a dictionary in the format :.

If two lists have the exact same dictionary output, we can infer that the lists are the same.

Note: The list order has no effect on the counter[] method.

Example:

import collections 


l1 = [10, 20, 30, 40, 50] 
l2 = [10, 20, 30, 50, 40, 70] 
l3 = [10, 20, 30, 40, 50] 

if collections.Counter[l1] == collections.Counter[l2]:
    print ["The lists l1 and l2 are the same"] 
else: 
    print ["The lists l1 and l2 are not the same"] 

if collections.Counter[l1] == collections.Counter[l3]:
    print ["The lists l1 and l3 are the same"] 
else: 
    print ["The lists l1 and l3 are not the same"] 

Output:

The lists l1 and l2 are not the same
The lists l1 and l3 are the same

3. Python sort[] method and == operator to compare lists

We can club the Python sort[] method with the == operator to compare two lists.

Python sort[] method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

Note: The order of the list does not affect this method because we’ll be sorting the lists before comparison.

Further, the == operator is used to compare the list, element by element.

Example:

import collections 


l1 = [10, 20, 30, 40, 50] 
l2 = [10, 20, 30, 50, 40, 70] 
l3 = [50, 10, 30, 20, 40] 

l1.sort[] 
l2.sort[] 
l3.sort[] 

if l1 == l3: 
    print ["The lists l1 and l3 are the same"] 
else: 
    print ["The lists l1 and l3 are not the same"] 


if l1 == l2: 
    print ["The lists l1 and l2 are the same"] 
else: 
    print ["The lists l1 and l2 are not the same"] 

Output:

The lists l1 and l3 are the same
The lists l1 and l2 are not the same

4. Python set[] method and == operator to compare two lists

Python set[] method manipulates the data items of an iterable to a sorted sequence set of data items without taking the order of elements into consideration.

Further, the == operator is used for comparison of the data items of the list in an element-wise fashion.

Example:

l1 = [10, 20, 30, 40, 50] 
l3 = [50, 10, 30, 20, 40] 

a = set[l1]
b = set[l3]

if a == b:
    print["Lists l1 and l3 are equal"]
else:
    print["Lists l1 and l3 are not equal"]

Output:

Lists l1 and l3 are equal

5. Python Custom List Comprehension to Compare Two Lists

We can use Python List comprehension to compare two lists.

Example:

l1 = [10, 20, 30, 40, 50] 
l3 = [50, 75, 30, 20, 40, 69] 

res = [x for x in l1 + l3 if x not in l1 or x not in l3]

print[res]
if not res:
    print["Lists l1 and l3 are equal"]
else:
    print["Lists l1 and l3 are not equal"]

 

In the above code, we set a pointer element ‘x’ to the list l1 and l3. Further, we check if the element pointed by the pointer element is present in the lists.

Output:

[10, 75, 69]
Lists l1 and l3 are not equal

Conclusion

Thus, in this article, we have covered and understood a number of ways to compare multiple lists in Python.

How do I compare two strings in a list?

Use the == and != operators to compare two strings for equality. Use the is operator to check if two strings are the same instance. Use the < , > , = operators to compare strings alphabetically.

How do you compare two elements in a list Python?

sort[] and == operator. The list. sort[] method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.

Can I use == to compare strings in Python?

Python comparison operators can be used to compare strings in Python. These operators are: equal to [ == ], not equal to [ != ], greater than [ > ], less than [ < ], less than or equal to [ = ].

How do you match a string to a list in Python?

Python Find String in List using count[] We can also use count[] function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.

Chủ Đề