Convert list of list to tuple

Contents

  • Introduction
  • Use tuple[] builtin function
  • Unpack List inside Parenthesis
  • Summary

Convert List to Tuple in Python

Because of the differences between a List and Tuple, you may need to convert a Python List to a Tuple in your application.

In this tutorial, we shall learn how to convert a list into tuple. There are many ways to do that. And we shall discuss the following methods with examples for each.

  • Use tuple[] builtin function.
  • Unpack List inside parenthesis.

Use tuple[] builtin function

tuple is a builtin Python class that can take any iterable as argument for its constructor and return a tuple object.

In the following example, we take a list and convert it to tuple using tuple[] constructor.

Python Program

list1 = ['Saranya', 'Surya', 'Manu'] #convert list into tuple tuple1 = tuple[list1] print[tuple1] print[type[tuple1]]Run

Output

['Saranya', 'Surya', 'Manu']

You may observe in the output that we have printed the type of the tuple1 object, which is .

Unpack List inside Parenthesis

We can also unpack the items of List inside parenthesis, to create a tuple.

In the following program, we have a list, and we shall unpack the elements of this list inside parenthesis.

Python Program

list1 = ['Saranya', 'Surya', 'Ritha', 'Joy'] #unpack list items and form tuple tuple1 = [*list1,] print[tuple1] print[type[tuple1]]Run

Output

['Saranya', 'Surya', 'Ritha', 'Joy']

Summary

In this tutorial of Python Examples, we learned how to convert a Python List into Tuple in different ways, with the help of well detailed example programs.

Related Tutorials

  • Python Sort List of Tuples
  • Python List of Tuples
  • Python Tuple vs List

Video liên quan

Chủ Đề