Convert Between a List and a Tuple in Python
In Python, you can convert between a list
and a tuple
using the list()
and tuple()
functions. These functions generate new list
or tuple
objects when given an iterable object, such as a list
, tuple
, set
, range
, etc.
Although the term "convert" is used, note that these functions actually create new objects, leaving the original objects unaffected.
In the following sample code, list
, tuple
, and range
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'>
For further details on range()
, see the following article.
Convert a tuple
to a list
with list()
By passing an iterable object, such as a tuple
, to list()
, you can generate a new list
that contains the elements of the passed iterable.
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'>
Convert a list
to a tuple
with tuple()
Similarly, by passing an iterable object, such as a list
, to tuple()
, you can generate a new tuple
that contains the elements of the passed iterable.
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'>
Add, change, and delete elements of a tuple
Since a tuple
is immutable, you cannot add, change, or remove its elements directly. However, you can convert a tuple
to a list
using list()
, modify the list
as needed, and then use tuple()
to create an updated tuple
.
For more details on manipulating tuples, see the following article.