Convert tuple to list
What You'll Learn: In this tutorial, you'll discover how to convert a Python tuple into a list. This is useful because lists and tuples have different properties, such as mutability.
Method 1: Using the list() Built-in Function
The list() function can take any iterable, like a tuple, and return a list object.
Example Code:
# Take a tuple of elements
tuple_1 = ('a', 'e', 'i', 'o', 'u')
# Convert tuple into list
list_1 = list(tuple_1)
print(list_1)
print(type(list_1))
Output:
['a', 'e', 'i', 'o', 'u']
<class 'list'>What's Happening Here?
list(tuple_1)converts the tupletuple_1into a listlist_1.
Method 2: Unpacking Tuple Inside Square Brackets
You can also convert a tuple to a list by unpacking the tuple inside square brackets [].
Example Code:
# Take a tuple of elements
tuple_1 = ('a', 'e', 'i', 'o', 'u')
# Convert tuple into list
list_1 = [*tuple_1,]
print(list_1)
print(type(list_1))
Output:
['a', 'e', 'i', 'o', 'u']
<class 'list'>What's Happening Here?
list_1 = [*tuple_1,]unpacks the elements oftuple_1inside square brackets, creating a listlist_1.
Try It Yourself: Fun Exercises
- Convert Your Favorite Colors:
- Create a tuple of your favorite colors.
- Convert this tuple to a list using the
list()function.
- Transform Your Snack List:
- Make a tuple of snacks you like.
- Convert this tuple to a list by unpacking the tuple inside square brackets.
Summary:
In this Python tutorial, we learned how to convert a tuple to a list using two methods: the list() function and unpacking the tuple inside square brackets. Lists are mutable, making them useful for scenarios where you need to change the items. Keep experimenting and have fun with tuples and lists in Python!