# How to remove element in list with a value

119
1
05-15-2019 02:14 AM New Contributor

Hi All,

I have a list called 'badItems' that I want to remove/delete, the second position within the tuple, if it is the same as my variable 'OBJ'. It will always be the second position but anywhere in the list.

badItems = [(2, 1), (2, 271), (2, 272), (2, 273), (2, 277)]

OBJ = 1

return badItems = [(2, 271), (2, 272), (2, 273), (2, 277)]

or like this:

badItems = (1, 2), (1, 4), (1, 273), (1, 533), (1, 805), (1, 1107), (1, 1108), (1, 1451), (1, 1452), (1, 1827), (1, 1828)]

OBJ = 273

return badItems = [(1, 2), (1, 4), (1, 533), (1, 805), (1, 1107), (1, 1108), (1, 1451), (1, 1452), (1, 1827), (1, 1828)]

This is what I have so far, cheers:

for row in tempDict.values():
#print "row " + str(row)
#print "tempDictValues " + str(tempDict)
obj = row
if obj not in tempDict:
obj += 1
try:
inFid = badRow #inFid = 1
nearFid = badRow #nearFid = 2
print "nearFid " + str(nearFid)
tempDict.pop(nearFid)
except:
pass

1 Solution

Accepted Solutions by MVP Esteemed Contributor

I would start by trying a list comprehension:

``````>>> badItems = [(2, 1), (2, 271), (2, 272), (2, 273), (2, 277)]
>>> OBJ = 1
>>> [(x,y) for x,y in badItems if y != OBJ]
[(2, 271), (2, 272), (2, 273), (2, 277)]
>>>‍‍‍‍‍`````` by ``````>>> badItems = [(2, 1), (2, 271), (2, 272), (2, 273), (2, 277)] 