Reputation: 51
a=[(1,2),(2,3),(3,5),(4,1)]
b=[(1,3),(2,3),(3,5),(4,3)]
I want to compare each element in the list according to their index number, namely the first item to the first item, the second item to the second item, and so on..
if they match, do nothing, it they don't match, append to new list.
Upvotes: 2
Views: 1752
Reputation: 71451
Using simple list comprehension:
a=[(1,2),(2,3),(3,5),(4,1)]
b=[(1,3),(2,3),(3,5),(4,3)]
new_list = [a[i] for i in range(len(a)) if a[i] != b[i]]
Upvotes: 0
Reputation: 78690
Vanilla:
>>> result = []
>>> for x, y in zip(a, b):
... if x != y:
... result.append(x)
... result.append(y)
...
>>> result
[(1, 2), (1, 3), (4, 1), (4, 3)]
Fun:
>>> sum(([x,y] for x,y in zip(a, b) if x != y), [])
[(1, 2), (1, 3), (4, 1), (4, 3)]
The general lesson you should learn here is that whenever you want to compare iterables element-wise, use the zip
builtin. Everything after that is completely straight forward (in the vanilla version).
Upvotes: 2
Reputation: 16720
Here is a solution using a classical for
loop.
l = []
for i in range(len(a)):
if a[i] != b[i]:
l.append(a[i])
l.append(b[i])
Upvotes: 0
Reputation: 5613
If the lists are the same length like the example you provided, and you want to append the two elements that don't match you can use:
a=[(1,2),(2,3),(3,5),(4,1)]
b=[(1,3),(2,3),(3,5),(4,3)]
c = []
for i in xrange(len(a)):
if a[i] != b[i]:
c.append(a[i])
c.append(b[i])
print c
output:
[(1, 2), (1, 3), (4, 1), (4, 3)]
Upvotes: 0