Convert lists and tuples to each other in Python
In Python, you can convert lists list and tuples tuple to each other by using list() and tuple().
For the sake of convenience, the word "convert" is used , but in reality a new object is generated, and the original object remains the same.
list() and tuple() return new list and tuple when given an iterable object such as list, tuple, set, range, etc.
- Built-in Functions - list() Python 3.8.5 documentation
- Built-in Functions - tuple() Python 3.8.5 documentation
In the following sample code, list, tuple, and range type objects are used as examples.
See the following article for details on range().
- How to use range() in Python
list()
By passing an iterable object such as tuple as an argument of list(), list with the elements of passed iterable is generated.
tuple()
By passing an iterable object such as list as an argument of tuple(), tuple with the elements of passed iterable is generated.
Add / change / delete tuple`s element
Since tuple is immutable, you can not add, change or remove elements, but after making list with list() and adding, changing, deleting elements of list, you can get updated tuple by using tuple() again.
See the following article for details.
- Update tuples in Python (Add, change, remove items in tuples)
Related Categories
- Python
- List
Related Articles
- Initialize a list with given size and values in Python
- Add an item to a list in Python (append, extend, insert)
- Convert numpy.ndarray and list to each other
- List comprehensions in Python
- enumerate() in Python: Get the element and index from a list
- Extract and replace elements that meet the conditions of a list of strings in Python
- Convert 1D array to 2D array in Python (numpy.ndarray, list)
- How to flatten a list of lists in Python
- Transpose 2D list in Python (swap rows and columns)
- Remove / extract duplicate elements from list in Python
- Convert pandas.DataFrame, Series and list to each other
- Sort a list of dictionaries by the value of the specific key in Python
- Reverse a list, string, tuple in Python (reverse, reversed)
- Queue, stack, and deque (double-ended queue) in Python
- Count elements from a list with collections.Counter in Python