Converting lists and tuples to each other in Python: list(), tuple()

Money and Business

When you want to convert lists (arrays) and tuples to each other in Python, use list() and tuple().

If iterable objects such as set types as well as lists and tuples are given as arguments, new objects of types list and tuple are returned.

The following list, tuple, and range type variables are 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'>

The range() returns an object of type range since Python 3.

Note that although the term “conversion” is used for convenience, the new object is actually created, and the original object remains intact.

Generate list: list()

When an iterable object such as a tuple is specified as the argument to list(), a list with that element 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'>

Generate tuples: tuple()

When an iterable object such as a list is specified as the argument to tuple(), a tuple with that element 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'>

Add or change elements of tuples

Tuples are immutable (not updatable), so elements cannot be changed or deleted. However, a tuple with elements changed or deleted can be obtained by using list() to make a list, changing or deleting elements, and then using tuple() again.

Copied title and URL