This is not a dupe of other questions I have found such as:
Remove items from a list while iterating
Python: Removing list element while iterating over list
The problem is this: given a list of classes, such as abstracted sockets, what is the most Pythonic way to remove them, if there is a non-trivial way of determining if they should be removed?
sockets = [ socket1, socket2, socket3 ] # whatever
for sock in sockets:
try:
sock.close()
except:
pass
else:
remove the socket from the list here!
Cannot use the solution from either link. The "best" solution I can think of with my limited Python knowledge is to create a new list with only the ones that encountered exceptions appended to it.
sockets = [ socket1, socket2, socket3 ] # whatever
newsockets = []
for sock in sockets:
try:
sock.close()
except:
newsockets.append(sock)
sockets = newsockets
This still feels wrong, however. Is there a better way?
EDIT for moderator who ignored my explicit statement that the question this was marked as a dupe of is not a dupe.
To the first link I posted, you cannot use try/except in a list comprehension.
To the second link (the one it was marked as a dupe of), as the comments say, that is a bad solution. remove(non-hashable item or item that doesn't have __eq__)
does not work.