How to convert List to Tuple in Python

This article covers the topic of converting a list to tuple. A list is a mutable collection of elements while a tuple is an immutable collection.
Method 1:
Typecasting the list into a tuple using tuple()
.
def convert(list): return tuple(list) list = [5, 2, 7, 1] print(convert(list))
Output:
(5, 2, 7, 1)
Method 2:
In this method, the list is unpacked inside a tuple literal which is created due to the presence of the single comma (, ). This approach is a faster when compared to the above mentioned method but suffers from readability.
def convert(list): return (*list, ) list = [5, 2, 7, 1] print(convert(list))
Output:
(5, 2, 7, 1)
Subscribe
Login
Please login to comment
0 Discussion