Convert tuple to list and back
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:
List to tuple:
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:
Going advanced with numpy
For intricate map updates, numpy arrays are the lightsabers (Don't cut yourself!):
Unpacking generalizations: Exploding tuples to lists, and imploding them back
Python 3.5 graced us with unpacking generalizations (PEP 448):
These methods work great for nested conversions.
Speed Comparison
Listing comprehension feels naturally pythonic, but for larger data sets, map function has the
speedforce:
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:
Also, for gigantic tuples, consider memory overhead during conversions.
Was this article helpful?