Call int() function on every list element?
To cast each list element to an integer, use a list comprehension:
This bite-sized piece of code directly converts string elements in nums to integers, assembling them into a new list ints.
Transforming lists: Beyond the basics
Memory-friendly generators
For giant lists, a generator expression can perform the conversion while saving memory:
A generator yields values one at a time — it's memory-efficient and ideal when dealing with massive data.
The magic of map and unpacking
The map() function paired with unpacking, offers an additional way for the conversion:
The * operator alongside map is like unwrapping a present, releasing the converted elements from their iterable wrapping into a list.
Comprehensions vs map: The showdown
Though similar in performance, list comprehensions and map() have strengths that might sway your preference. map() is concise, while comprehensions are often more self-explanatory. Choose based on readability.
Tricky scenarios and solutions
Handling mixed-type lists
Non-string elements can throw a spanner in the works. Be ready with this approach:
This safeguards your code, applying int() only to strings, and dodges potential TypeError landmines.
Safeguarding against conversion errors
Unconvertible string elements in your list? Keep calm and handle errors:
This ensures safe conversion, non-convertible elements return None.
The functional style with map
The strategy above can be mirrored using map(), where you provide a function as an argument:
This approach safely maps the function onto each list element.
Python versions and their quirks
Python 2.x caveats with map
If you're time-traveling in Python 2.x, beware: map() behaves a bit differently:
There's no need to use list conversion or unpacking as map() hands you a list right off the bat.
Was this article helpful?