
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert a List into a Tuple in Python
List and Tuple in Python are classes of data structures. The list is dynamic, whereas the tuple has static characteristics. In this article, we will convert a list into a tuple by using a few methods. Each of these methods is discussed below.
Converting List into Tuple using tuple()
We can convert a list into a tuple using the tuple() function. This function accepts a list as a parameter, converts into a tuple and returns the result.
Example 1
In the following program, we convert a list to a tuple using the tuple() function.
# using tuple() built-in function list_names=['Meredith', 'Kristen', 'Wright', 'Franklin'] # convert list to tuple tuple_names= tuple(list_names) # print the tuple print(tuple_names) print(type(tuple_names))
When you run the program, it will show this output -
('Meredith', 'Kristen', 'Wright', 'Franklin') <class 'tuple'>
Example 2
Here is another example of using the tuple() built-in function to convert a list to a tuple.
# Define a list my_list = [1, 2, 3] # Convert list to tuple my_tuple = tuple(my_list) # Print the tuple print(my_tuple)
After running the program, you will get this result -
(1, 2, 3)
Converting List toTuple using loops
To convert a List to a Tuple using loops we need to retrieve each element from the list using a for loop to send it as an argument to the tuple() function.
Example
The following is a program to convert a list to a tuple using a loop.
# Define a list list_names=['Meredith', 'Kristen', 'Wright', 'Franklin'] # Convert list to tuple using a loop tuple_names = tuple(i for i in list_names) # Print the tuple print(tuple_names) print(type(tuple_names))
This output will be displayed when the program runs -
('Meredith', 'Kristen', 'Wright', 'Franklin') <class 'tuple'>
Unpack List in Parenthesis
Using the unpack operator, "*" we can unpack the elements of a list within the paranthesis and assign it to a variable.
Example
In this example, we use the unpacking method to convert a list to a tuple.
list_names=['Meredith', 'Kristen', 'Wright', 'Franklin'] tuple_names= (*list_names,) print(tuple_names) print(type(tuple_names))
You will see this result after executing the program -
('Meredith', 'Kristen', 'Wright', 'Franklin') <class 'tuple'>