[Solved] – Python – Convert list to tuple in Python

Convert list to tuple in Python

Asked on October 19, 2018 in Python.
Add Comment


  • 5 Answer(s)

    It ought to work fine. do not use tuple, list or different special names as a variable name. It’s most likely what is inflicting your drawback.

    >>> l = [4,5,6]
    >>> tuple(l)
    (4, 5, 6)
    
    Answered on October 19, 2018.
    Add Comment

    Expanding on eumiro’s comment, usually tuple(l) can convert an inventory l into a tuple:

    In [1]: l = [4,5,6]
    In [2]: tuple
    Out[2]: <type 'tuple'>
    In [3]: tuple(l)
    Out[3]: (4, 5, 6)
    

    However, if you’ve redefined tuple to be a tuple rather than the type tuple:

    In [4]: tuple = tuple(l)
    In [5]: tuple
    Out[5]: (4, 5, 6)
    
    In [6]: tuple(l)
    TypeError: 'tuple' object is not callable
    
    In [6]: del tuple
    In [7]: tuple
    Out[7]: <type 'tuple'>
    
    Answered on October 19, 2018.
    Add Comment

    You might have done something like this:

    >>> tuple = 45, 34 # You used `tuple` as a variable here
    >>> tuple
    (45, 34)
    >>> l = [4, 5, 6]
    >>> tuple(l) # Will try to invoke the variable `tuple` rather than tuple type.
    Traceback (most recent call last):
        File "<pyshell#10>", line 1, in <module>
            tuple(l)
    TypeError: 'tuple' object is not callable
    >>>
    >>> del tuple # You can delete the object tuple created earlier to make it work
    >>> tuple(l)
    (4, 5, 6)
    

    Here’s the matter… Since you have got used a tuple variable to carry a tuple (45, 34) earlier… So, currently tuple is Associate in Nursing object of sort tuple currently…
    It is no additional a sort and thus, it’s no additional due .
    Never use any constitutional sorts as your variable name… you are doing have the other name to use. Use any impulsive name for your variable instead…

    Answered on October 19, 2018.
    Add Comment

    Example code,

    #Convert list to tuple
    listx = [5, 10, 7, 4, 15, 3]
    print(listx)
    #use the tuple() function built-in Python, passing as parameter the list
    tuplex = tuple(listx)
    print(tuplex)
    
    Answered on December 19, 2018.
    Add Comment

    Here is your sample code,

    # Python code to convert into dictionary
    def Convert(tup, di):
         for a, b in tup:
            di.setdefault(a, []).append(b)
         return di
    # Driver Code
    tups = [("akash", 10), ("gaurav", 12), ("anand", 14),
            ("suraj", 20), ("akhil", 25), ("ashish", 30)]
    dictionary = {}
    print (Convert(tups, dictionary))
    
    Answered on December 19, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.