Technology3 min read

Python | Converting a List into a Tuple

Abhishek Ahlawat

By Abhishek Ahlawat โ€” Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

#Python#Python Tuple#Python List

Summarize this article using AI

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.

Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next