Programming Tutorials

Convert between tuples and lists in python

By: Rajesh in Python Tutorials on 2012-04-07  

The type constructor tuple(seq) converts any sequence (actually, any iterable) into a tuple with the same items in the same order.

For example, tuple([1, 2, 3]) yields (1, 2, 3) and tuple('abc') yields ('a', 'b', 'c'). If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call tuple() when you aren't sure that an object is already a tuple.

The type constructor list(seq) converts any sequence or iterable into a list with the same items in the same order. For example, list((1, 2, 3)) yields [1, 2, 3] and list('abc') yields ['a', 'b', 'c']. If the argument is a list, it makes a copy just like seq[:] would.

Converting a tuple to a list:

my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)  # Output: [1, 2, 3]

In this example, the list() function is used to convert the tuple (1, 2, 3) to a list [1, 2, 3]. The resulting list is stored in the my_list variable and printed to the console.

Converting a list to a tuple:

my_list = [4, 5, 6]
my_tuple = tuple(my_list)
print(my_tuple)  # Output: (4, 5, 6)

In this example, the tuple() function is used to convert the list [4, 5, 6] to a tuple (4, 5, 6). The resulting tuple is stored in the my_tuple variable and printed to the console.

Note that when you convert a mutable data type like a list to an immutable data type like a tuple, any modifications made to the original list after the conversion will not affect the new tuple. Similarly, if you convert an immutable data type like a tuple to a mutable data type like a list, you can modify the resulting list without affecting the original tuple.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Python )

Latest Articles (in Python)