How do I convert all of the items in a list to floats?
Convert a list to floats with list comprehension:
Replace your_list
with your own list. Also, buckle up, this ride is only for Python 3.
Breakdown: different approaches and their nuances
Transform string to float: the classic way
Use map
function to call float
on every string:
For the hungry data-beast: NumPy
When dealing with impossibly long lists for scientific calculations, NumPy comes to the rescue with its furious speed:
dtype is strictly defined for pure-blooded float conversion.
In-place modifications: going rogue with enumerate
Change the elements inside your original list without creating a new one:
Key considerations for surprising hurdles on the road
Test before you leap: pre-check data types
Before jumping to convert, check if the leap is safe. Not everything that glitters is float:
Beware of the shadow: don't shadow built-in names
Choose variable names wisely. Naming your pet python float
, str
or list
might lead to an identity crisis!
Race of efficiency: list comprehension, map
or numPy?
While list comprehension and map
take the cake for readability, numpy
has unmatched speed when it comes to big-numbers competitions.
Was this article helpful?