Convert lists and tuples to each other in PythonPosted: 2020-07-22 / Tags: Python, List Tweet In Python, you can convert lists list and tuples tuple to each other by using list() and tuple(). Show 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.
In the following sample code, list, tuple, and range type objects are used as examples. l = [0, 1, 2]
print(l)
print(type(l))
# [0, 1, 2]
# <class 'list'>
t = ('one', 'two', 'three')
print(t)
print(type(t))
# ('one', 'two', 'three')
# <class 'tuple'>
r = range(10)
print(r)
print(type(r))
# range(0, 10)
# <class 'range'>
source: list_tuple.py See the following article for details on range().
Sponsored Link list()By passing an iterable object such as tuple as an argument of list(), list with the elements of passed iterable is generated. tl = list(t)
print(tl)
print(type(tl))
# ['one', 'two', 'three']
# <class 'list'>
rl = list(r)
print(rl)
print(type(rl))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# <class 'list'>
source: list_tuple.py tuple()By passing an iterable object such as list as an argument of tuple(), tuple with the elements of passed iterable is generated. lt = tuple(l)
print(lt)
print(type(lt))
# (0, 1, 2)
# <class 'tuple'>
rt = tuple(r)
print(rt)
print(type(rt))
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# <class 'tuple'>
source: list_tuple.py Sponsored Link Add / change / delete tuple`s elementSince 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.
Sponsored Link Share TweetRelated Categories
Related Articles
|