Search code examples
python-2.7settuplesargs

function that takes variable length as argument and returns tuple


I have written code as below:

def convTup(*args):
    t = set([])
    for i in args:
        t.add(i)
    return tuple(t)

print convTup('a','b','c','d')
print convTup(1,2,3,4,5,6)
print convTup('a','b')

Expected output :

('a', 'b', 'c', 'd')
(1, 2, 3, 4, 5, 6)
('a', 'b')

But I got output as below:

('a', 'c', 'b', 'd')
(1, 2, 3, 4, 5, 6)
('a', 'b')

Why has the order of the elements changed only for ('a','b','c','d')? How can I print the tuple in the same order as the given input?


Solution

  • You can use this and you'll have a tuple sequence as your input

    >>> def f(*args):
        p = []
        [p.append(x) for x in args if x not in p]
        return tuple(p)
    
    >>> f(1, 1, 2, 3)
    (1, 2, 3)
    >>> f('a', 'b', 'c', 'd')
    ('a', 'b', 'c', 'd')
    

    This function will create a list of unique elements and track their order then return it as a tuple.

    You can see the same functionality using a set instead of list. A set doesn't keep track of the order the elements were entered.

    >>> def tup1(*args):
        l = {x for x in args}
        return tuple(l)
    
    >>> 
    >>> tup1('a', 'b', 'c', 'd')
    ('a', 'c', 'b', 'd')
    

    You can implement your own SortedSet collection if you use it in multiple places.