I have a list of tuples and I want to create another list that doesn't contain a specific tuple from that list.
Example:
mylist = [(a,b), (c,d), (e,f)]
selected = (c,d)
operation_between(list, selected)
newlist = [(a,b), (e,f)]
The most simple way to do that is using a for loop, for iterating through mylist and inserting to newlist if current_item != selected
. Is there any better way?
I thought of converting the list to a set and then using the -
operator to remove the selected tuple from the set. But using set(mylist)
only created a set with one item, the list.
Then to fix that I think to use list comprehension, but this implies a for-loop again.
Maybe just make a list comprehension filtering for what you don't want?
mylist2 = [(x, y) for (x, y) in mylist if (x, y) != (c, d)]
Use list.remove()
if you want to alter mylist
:
mylist.remove(selected)
If you want a new copy of mylist
without the element in question, use the list()
constructor to make a new list instead, then call remove()
on the new list:
newlist = list(mylist)
newlist.remove(selected)
Use the function del
, to delete a tuple
from a list
.
def operation_between(list, selected):
newlist = list
del(newlist[newlist.index(selected)])
return newlist
I have a list of tuples and I want to create another list that doesn't contain a specific tuple from that list.
Example:
mylist = [(a,b), (c,d), (e,f)]
selected = (c,d)
operation_between(list, selected)
newlist = [(a,b), (e,f)]
The most simple way to do that is using a for loop, for iterating through mylist and inserting to newlist if current_item != selected
. Is there any better way?
I thought of converting the list to a set and then using the -
operator to remove the selected tuple from the set. But using set(mylist)
only created a set with one item, the list.
Then to fix that I think to use list comprehension, but this implies a for-loop again.
Maybe just make a list comprehension filtering for what you don't want?
mylist2 = [(x, y) for (x, y) in mylist if (x, y) != (c, d)]
Use list.remove()
if you want to alter mylist
:
mylist.remove(selected)
If you want a new copy of mylist
without the element in question, use the list()
constructor to make a new list instead, then call remove()
on the new list:
newlist = list(mylist)
newlist.remove(selected)
Use the function del
, to delete a tuple
from a list
.
def operation_between(list, selected):
newlist = list
del(newlist[newlist.index(selected)])
return newlist
0 commentaires:
Enregistrer un commentaire