'I want to compare list of two cities and if list B cities are not present in list A then should append in list A using python

A=['mumbai','delhi','jaipur']
B=['mumbai','kolkata','pune']

I want to compare list A and list B and if list B cities are not in list A then we should able to append those cities in list A



Solution 1:[1]

One more way to do the same but not by using the for loop.

difference_between_lists = list(set(B) - set(A))
A += difference_between_lists

Solution 2:[2]

You loop through list B and check if the item in list B is in list A. If it is, don't do anything, if it isn't, append it to list A.

for i in B:
    if not i in A:
        A.append(i)

Solution 3:[3]

You can also do this using list comprehension

C = [i for i in B if not i in A]
print(A+C)

Solution 4:[4]

You can also use sets and do the union.

setA = set(A)
setB = set(B)
print(setB.union(setA))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michel Keijzers
Solution 2 Itik
Solution 3 Python learner
Solution 4