Reputation: 85
So the problem is that I have a list which is made of pairs of numbers [ (0,0),(0,1)(0,2) ...etc and I would like to know how to delete from this list all pairs with the same numbers . List was created by this function.
l1 = []
def fun2(x,y):
for x in range(x+1):
for y in range(y+1):
l1.append((x,y))
return l1
Upvotes: 0
Views: 86
Reputation: 87064
You can avoid duplicate tuple elements while generating the list. Just add an if
:
def fun2(x, y):
result = []
for a in range(x+1):
for b in range(y+1):
if a != b:
result.append((a,b))
return result
This could also be written more succinctly as a list comprehension:
result = [(a, b) for a in range(x+1) for b in range(y+1) if a != b]
Yet another option is to use itertools.product()
:
from itertools import product
result = [(a, b) for a, b in product(range(x+1), range(y+1)) if a != b]
Removing items afterwards is also possible with a list comprehension:
result = [pair for pair in result if pair[0] != pair[1]]
which creates a new list without the duplicate items then rebinds it to result
. You can overwrite the list in place with:
result[:] = [pair for pair in result if pair[0] != pair[1]]
Upvotes: 5
Reputation: 2076
Method 1: Using list comprehnsion:
lst = [c for c in l1 if c[0] != c[1]]
Method 2: Building the list manually:
lst = []
for elem in l1:
if elem[0] != elem[1]:
lst.append(elem)
Upvotes: 0