Convert a List to a Tuple in Python
This post will discuss how to convert a list to a tuple in Python.
1. Using tuple constructor
The simplest way to convert a list to a tuple in Python is to use the built-in tuple() constructor. This function takes an iterable object as an argument and construct a tuple from elements of the iterable in same order. The iterable can either be a sequence (such as a list, string, tuple, or range), or collection (such as a dictionary or set).
For example, tuple([10, 20, 30]) returns (10, 20, 30). The following example demonstrates this.
|
1 2 3 4 |
l = [10, 20, 30] t = tuple(l) print(t) # (10, 20, 30) |
2. Using unpacking syntax
Another way to convert a list to a tuple in Python is to use unpacking syntax, which allows us to assign multiple values from an iterable to multiple variables. We can use it to create a new tuple object by unpacking the arguments of a list inside a tuple with the * operator. Here’s what the code would look like:
|
1 2 3 4 |
l = [10, 20, 30] t = (*l,) print(t) # (10, 20, 30) |
3. Using comprehension syntax
Another option to convert a list to a tuple is using the comprehension syntax, which allows us to create new iterable objects (such as tuples or lists) from existing ones. We can use it to create a generator object by using parentheses () around the expression. To get the actual tuple object, we can pass the generator object to the tuple() constructor. For example:
|
1 2 3 4 |
l = [10, 20, 30] t = tuple(x for x in l) print(t) # (10, 20, 30) |
This method is useful if we want to apply some logic or transformation on each element of the list before converting it to a tuple. For example, we can use this method to create a tuple of squares from a list of numbers.
|
1 2 3 4 |
l = [1, 2, 3, 4, 5] t = tuple(x**2 for x in l) print(t) # (1, 4, 9, 16, 25) |
That’s all about converting a List to a Tuple in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)