Explain Codes LogoExplain Codes Logo

Convert tuple to list and back

python
list
tuple
conversions
Anton ShumikhinbyAnton Shumikhin·Jan 9, 2025
TLDR

Turn a tuple into a list using list(), a built-in function which allows element modifications. Make a list unmutable again by converting it to a tuple with tuple().

Tuple to list:

my_tuple = (1, 2, 3) my_list = list(my_tuple) # Freedom of change!

List to tuple:

my_list = [1, 2, 3] my_tuple = tuple(my_list) # Freeze! You're immutable now.

Switching between tuple and list is handy when you require mutable structures temporarily, but wants data integrity ensured by tuple's immutability.

Nitty-gritty details and use-cases

Editing map data: tuple-list switch hitting the rescue

In a map editor, typically, maps are denoted as tuples of tuples representing blocks ("1" for walls, "0" for air). Now, say you want to update a block type; for this, conversion to list is handy as it renders the map editable:

# Map data as tuple of tuples map_data = ((1, 0, 1), (0, 1, 0), (1, 0, 1)) # Convert to list of lists to enable edits editable_map = [list(row) for row in map_data] # Let's place Rick's portal gun at (1, 1) editable_map[1][1] = 9 # Poof, we made a portal! # Convert back to tuple of tuples for stability map_data = tuple(tuple(row) for row in editable_map)

Going advanced with numpy

For intricate map updates, numpy arrays are the lightsabers (Don't cut yourself!):

import numpy as np # A new map data as numpy array map_data = np.array(map_data) # Placing a plumbus at (1, 2) with numpy is easy-peasy map_data[1, 2] = 15 # New day, new plumbus # Revert numpy array back to tuple of tuples map_data = tuple(map(tuple, map_data))

Unpacking generalizations: Exploding tuples to lists, and imploding them back

Python 3.5 graced us with unpacking generalizations (PEP 448):

# A nested tuple of tuples (tuples all the way down) nested_tuple = ((1, 2), (3, 4)) # Convert inner tuples to lists (Inception: Exploding the dreams) unpacked_to_list = [[*sub] for sub in nested_tuple] # Imploding dreams to reality: Lists to tuples repacked_to_tuple = tuple(tuple(sub) for sub in unpacked_to_list)

These methods work great for nested conversions.

Speed Comparison

Listing comprehension feels naturally pythonic, but for larger data sets, map function has the

speedforce:

# Big tuple, big ambitions big_tuple = tuple(range(1000)) # Converting to list during a Flash run big_list = list(map(list, big_tuple)) # You won't see the Flash running

It's smart to use benchmarking tools like timeit for checking performance ratio of your code.

Watch your steps!

tC_Warning of mutable elements lurking within tuples like a Xenomorph in vents. Converting to a list and back won't make them suddenly benign:

my_tuple = (1, [2, 3], 4) my_list = list(my_tuple) my_list[1].append(5) # Gotcha! Nested list still mutable. my_tuple = tuple(my_list)

Also, for gigantic tuples, consider memory overhead during conversions.