Convert List to Tuple

 

What You'll Learn: In this tutorial, you'll discover how to convert a Python list to a tuple. Lists and tuples are both ways to store multiple items, but sometimes you need to convert between them for different uses.

Method 1: Use the tuple() Built-in Function

The tuple() function can take any iterable as an argument and return a tuple object.

Example Code:

python
# Take a list of elements
list1 = ['apple', 'banana', 'cherry']
# Convert list into tuple
tuple1 = tuple(list1)
print(f'Tuple: {tuple1}')
print(type(tuple1))

Output:  

Tuple: ('apple', 'banana', 'cherry')
<class 'tuple'>

What's Happening Here?

  • tuple(list1) converts the list list1 into a tuple tuple1.

Method 2: Unpack List Inside Parentheses

You can also unpack the items of a list inside parentheses to create a tuple.

Example Code:

python
# Take a list of elements
list1 = ['apple', 'banana', 'cherry']
# Unpack list items and form tuple
tuple1 = (*list1,)
print(f'Tuple: {tuple1}')
print(type(tuple1))

Output: 

Tuple: ('apple', 'banana', 'cherry')
<class 'tuple'>

What's Happening Here?

  • (*list1,) unpacks the elements of list1 inside parentheses, forming tuple1.

Try It Yourself: Fun Exercises

  1. Convert Your Favorite Colors:
    • Create a list of your favorite colors.
    • Convert this list to a tuple using the tuple() function.
  2. Transform Your Shopping List:
    • Write a list of items you want to buy.
    • Convert this list to a tuple by unpacking the list inside parentheses.

Summary:

In this Python tutorial, we learned how to convert a list to a tuple using two methods: the tuple() function and unpacking the list inside parentheses. Converting between lists and tuples allows you to use the right data structure for your needs. Keep experimenting and have fun with lists and tuples in Python!