Example my 2 list are.
a = [11,22]
b = [33,22,11,44,55]
My expected output should add missing values from b into a in a sequential order.
a = [11,22,33,44,55]
This is my codes to achieve the output
z = (set(b).difference(a))
y = list(z)
for i in y:
a.append(i)
However if I print(y) it is [33,55,44], why is it not returning [33,44,55]? and how do i achieve my desired output.
CodePudding user response:
It's not adding in sequential order because you are using set
and the output can be different every try. You can use list comprehension to achieve this goal.
a = [11,22]
b = [33,22,11,44,55]
a = [element for element in b if element not in a]
CodePudding user response:
You can use set()
method to sort z
.
Corrected code :-
a = [11,22]
b = [33,22,11,44,55]
z = set((set(b).difference(a)))
y = list(z)
for i in y:
a.append(i)
print(a)
CodePudding user response:
a = [11,22]
b = [33,22,11,44,55]
c = list(set(a b))
c.sort()
print(c)
Output:
[11, 22, 33, 44, 55]
CodePudding user response:
a = [11,22]
b = [33,22,11,44,55]
for item in set(b):
if item not in a:
a.append(item)
print(a)
Loop through each element of second list(b), add in list(a) if element is not present