Convert tuple to list Python
In this post, you will learn how to convert a list to tuple using Python programming language.
A tuple is a sequence. Python Tuples work exactly like a list except tuples are immutable, means it cannot be changed in place. The tuples are written inside parentheses. The tuple length is always fixed. Tuple is easy to debug even in major projects. It consumes less memory. It provides less in-built methods. We can use dir([object]) inbuilt function to get all the associated functions for list and tuple.
A list is an arranged collection of elements. It is used to store collections of data. It can contain a list of various types of data objects with a comma separated and enclosed within a square bracket. It is mutable, which means we can change the order of elements, individual elements can be replaced even after the list has been created. This is one of the leading reasons why lists are being used widely. Lists play an effective role in small projects as it consumes more memory. It has many in-built methods.
Both, list and tuple are widely used to store data in Python. The difference between tuple and list is that tuple stores heterogeneous data while the list stores homogeneous data. During the development process, we may come to the situation where we need to convert a tuple to a list.
Using built-in function list()
Python provides a built-in function list() that take any iterable as an argument and convert it into a list object. In the given example, we have passed the entire tuple as a parameter within the list() function, it will return the list data type as an output.
Output of the above code:
x_tuple = ('pizza', 'burger', 'cookies', 'milkshake') #convert tuple into list x_list = list(x_tuple) print(x_list) print(type(x_list))
['pizza', 'burger', 'cookies', 'milkshake'] <class 'list'>
Using unpack tuple (*tuple, )
We can unpack the tuple items inside the square brackets to convert a tuple to a list. It unpacks the items inside the list literal in the presence of a single comma(,). The following example demonstrates this -
Output of the above code:
x_tuple = ('tea', 'coffee', 'cookies', 'juice', 'milkshake') #convert tuple into list x_list = [*x_tuple,] print(x_list) print(type(x_list))
['tea', 'coffee', 'cookies', 'juice', 'milkshake']
Related ArticlesConvert Python list to numpy array
Convert string to list Python
Python program to list even and odd numbers of a list
Python loop through list
Sort list in descending order Python
Convert array to list Python
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Python for loop index
Convert List to Dataframe Python
numpy random choice
Dictionary inside list python
Check if list is empty Python
Python raise keyword
Python program to get the largest number from a list
Python program to map two lists into a dictionary