
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Converting all strings in list to integers in Python
Sometimes we can have a list containing strings but the strings themselves are numbers and closing quotes. In such a list we want to convert the string elements into actual integers.
With int()
The int function takes in parameters and converts it to integers if it is already a number. So we design a for loop to go through each element of the list and apply the in function. We store the final result into a new list.
Example
listA = ['5', '2','-43', '23'] # Given list print("Given list with strings : \n",listA) # using int res = [int(i) for i in listA] # Result print("The converted list with integers : \n",res)
Output
Running the above code gives us the following result −
Given list with strings : ['5', '2', '-43', '23'] The converted list with integers : [5, 2, -43, 23]
With map and list
The map function can be used to apply int function into every element that is present as a string in the given list.
Example
listA = ['5', '2','-43', '23'] # Given list print("Given list with strings : \n",listA) # using map and int res = list(map(int, listA)) # Result print("The converted list with integers : \n",res)
Output
Running the above code gives us the following result −
Given list with strings : ['5', '2', '-43', '23'] The converted list with integers : [5, 2, -43, 23]
- Related Articles
- Converting list string to dictionary in Python
- Python – Strings with all given List characters
- Python Program – Strings with all given List characters
- Converting Strings to Numbers in C/C++
- Converting strings to snake case in JavaScript
- Python - Find all the strings that are substrings to the given list of strings
- Convert number to list of integers in Python
- Convert list of numerical string to list of Integers in Python
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- converting array to list in java
- Python - Group contiguous strings in List
- Python – All occurrences of Substring from the list of strings
- Converting Strings to Numbers and Vice Versa in Java.
- How to remove empty strings from a list of strings in Python?

Advertisements