In Python, you can convert a list of numeric strings to a list of integers by calling the int()
method on every element of the list, for example, using list comprehension, like so:
items = ['5', '-7', '1', '-2'] new_list = [int(item) for item in items] print(new_list) # [5, -7, 1, -2]
The code above would create a new list with all numeric strings in the list converted to integers. This is equivalent to the following, which uses map()
:
items = ['5', '-7', '1', '-2'] new_list = list(map(lambda item: int(item), items)) print(new_list) # [5, -7, 1, -2]
However, using list comprehension provides a more readable and concise syntax. For that reason, it is generally preferred and would be the recommended way.
For completeness sake, you can also achieve the same result with a simple loop:
items = ['5', '-7', '1', '-2'] new_list = [] for item in items: new_list.append(int(item)) print(new_list) # [5, -7, 1, -2]
However, it might not be the best choice as it would create/overwrite a variable named "item
", which would persist even after the loop completes:
items = ['5', '-7', '1', '-2'] new_list = [] for item in items: new_list.append(int(item)) print(item) # -2
Hope you found this post useful. It was published . Please show your love and support by sharing this post.