Signup/Sign In
LAST UPDATED: NOVEMBER 3, 2019

Python | Converting a List into a Tuple

    We all know what a python list is and what python tuple data structure is. The only significant difference between the data structures being, the list is mutable whereas tuple is immutable. Sometimes, it might be required to make a list immutable to retain the contents present inside it. This can be done by converting a list into a tuple.

    In this post, we will see various methods that can be employed to convert a list into a tuple.




    1. Typecasting the list into a tuple

    This is the simplest way in which a list can be converted into a tuple. After a list has been defined, it can simply be typecasted into a tuple by passing the name of the list to the tuple.


    Time for an example:

    my_list = [12, 'a', "StudyTonight", 3.67] 
    print(my_list)
    print(type(my_list))
    
    my_tuple = tuple(my_list)
    print(my_tuple)
    print(type(my_tuple))

    Output:

    [12, 'a', 'StudyTonight', 3.67]
    <class 'list'>
    (12, 'a', 'StudyTonight', 3.67)
    <class 'tuple'>

    Note: In production code, this can be wrapped in a method and then called wherever required.




    2. Unpacking a list into a tuple

    This can be achieved with the help of the * operators. This is technique is considerably quicker but makes the code less readable. It unpacks the list my_list inside a tuple literal my_tuple which is created with every data element of the list.


    Time for an example:

    my_list = [12, 'a', "StudyTonight", 3.67] 
    my_tuple = *my_list,
    print(my_tuple) 
    print(type(my_tuple))

    Output:

    (12, 'a', 'StudyTonight', 3.67)
    <class 'tuple'>



    3. Iterating over elements in the list and converting them into a tuple

    Once the list has been created, we can use a for loop to iterate over a list and populate the values into our tuple.


    Time for an example:

    my_list = [12, 'a', "StudyTonight", 3.67] 
    my_tuple = tuple(element for element in my_list)
    print(my_tuple) 
    print(type(my_tuple))

    Output:

    (12, 'a', 'StudyTonight', 3.67)
    <class 'tuple'>



    Conclusion

    We saw how a mutable data structure can be converted into an immutable data structure. Let us know how you would approach such a requirement in the comments below.

    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS