How to remove element in list with a value

352
1
Jump to solution
05-15-2019 02:14 AM
AndrewNeedham1
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[0]
    if obj not in tempDict:
        obj += 1
    try:
        badItems = [item for item in dissolvedBadList if item[0] == obj] #badItems =[(1,2),(1,4),(1,273)]
        print "badItems " + str(badItems)
        for badRow in badItems: #badRow = (1,2)
            inFid = badRow[0] #inFid = 1
            nearFid = badRow[1] #nearFid = 2
            print "nearFid " + str(nearFid)
            tempDict.pop(nearFid)
        dissolvedBadList.remove(obj) #this does not work
    except:
        pass

0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
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)]
>>>

View solution in original post

1 Reply
JoshuaBixby
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)]
>>>