How to remove the first instance of an element in a tuple?

  • A+
Category:Languages

So for example, I have a tuple:

(7, 5, 3, 3, 6, 3, 9) 

and I would want to take out only the first number 3 in that tuple so that it would look like this instead:

(7, 5, 3, 6, 3, 9) 

The code I've written uses the filter tool to take out the 3, however it takes out all the other 3's as well:

def takeOut(k, r):     newK = tuple(filter(lambda x: x != r, k))     return newK  print(takeOut((7, 5, 3, 3, 6, 3, 9), 3)) 

 


I'd go with slicing:

def remove_element(seq, element):     try:         index = seq.index(element)         return seq[:index] + seq[index + 1:]     except ValueError:  # element doesn't exist         return seq 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: