Mark Needham

Thoughts on Software Development

Python: (Conceptually) removing an item from a tuple

with 6 comments

As part of some code I’ve been playing around I wanted to remove an item from a tuple which wasn’t particularly easy because Python’s tuple data structure is immutable.

I therefore needed to create a new tuple excluding the value which I wanted to remove.

I ended up writing the following function to do this but I imagine there might be an easier way because it’s quite verbose:

def tuple_without(original_tuple, element_to_remove):
    new_tuple = []
    for s in list(original_tuple):
        if not s == element_to_remove:
            new_tuple.append(s)
    return tuple(new_tuple)

Which can be used like so:

>>> tuple_without((1,2,3,4), 1)
(2, 3, 4)
>>> tuple_without((1,2,3,4), 0)
(1, 2, 3, 4)

The easiest approach seemed to be to build up a list containing all the values and then convert it to a tuple by using the tuple function.

It’d be cool if there was a way to transform a tuple like this but I couldn’t find such a function in my travels.

Written by Mark Needham

January 27th, 2013 at 2:30 am

Posted in Python

Tagged with

  • xjtian

    You could use a list comprehension to make the function more Pythonic:
        return tuple([x for x in original_tuple if x != element_to_remove])

  • Aivars Kalvāns

    Or you could use list methods to remove the element:
    def tuple_without(original_tuple, element_to_remove):
    lst = list(original_tuple)
    lst.remove(element_to_remove)
    return tuple(lst)

  • http://www.markhneedham.com/blog Mark Needham

    @google-4fbb3330aeb90297b9db1d9ad8b7075f:disqus @ab4ef97880b6e54f4298b3700b713586:disqus ah nice! Some cleaner alternatives, good stuff.

  • http://junctionbox.ca/ nfisher

    itertools ifilter would work in a pinch;

    def tuple_without(original_tuple, element_to_remove):

          return tuple(ifilter(lambda i: i != element_to_remove, original_tuple))

  • http://junctionbox.ca/ nfisher

    Actually it can be simplified further;

    
    def tuple_without(original_tuple, element_to_remove):
        return filter(lambda el: el != element_to_remove, original_tuple)
    
  • deadpool

    return tuple(x for x in original_tuple if x != element_to_remove)

    You can lose the ‘[',']‘