- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert list of numerical string to list of Integers in Python
For data manipulation using python, we may come across scenario where we have strings containing numbers in a list. To be able to make calculations, we will need to change the strings into numbers. In this article we will see the ways to change the strings into numbers inside a list.
With int
The int function can be applied to the string elements of a list converting them to integers . We have to carefully design the for loops to go through each element and get the result even if there are multiple strings inside a single element.
Example
listA = [['29','12'], ['25'], ['70']] # Given lists print("Given list A: ", listA) # Use int res = [[int(n) for n in element] for i in listA for element in i] # Result print("The numeric lists: ",res)
Output
Running the above code gives us the following result −
Given list A: [['29', '12'], ['25'], ['70']] The numeric lists: [[2, 9], [1, 2], [2, 5], [7, 0]]
With map
We can also use the map function which will apply a given function again and again to each parameter that is supplied to this function. We create a for loop which fetches the elements form each of the inner lists. This approach does not work if the inner lists have multiple elements inside them.
Example
listA = [['29'], ['25'], ['70']] # Given lists print("Given list A: ", listA) # Use map res = [list(map(int, list(elem[0]))) for elem in listA if elem ] # Result print("The numeric lists: ",res)
Output
Running the above code gives us the following result −
Given list A: [['29'], ['25'], ['70']] The numeric lists: [[2, 9], [2, 5], [7, 0]]
- Related Articles
- Convert list of string to list of list in Python
- Python - Convert list of string to list of list
- Convert number to list of integers in Python
- Convert string enclosed list to list in Python
- Convert list of string into sorted list of integer in Python
- What is the lambda expression to convert array/List of String to array/List of Integers in java?
- Convert a string representation of list into list in Python
- Convert list of tuples to list of list in Python
- Program to convert List of Integer to List of String in Java
- Program to convert List of String to List of Integer in Java
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- How to convert list to string in Python?
- Python - Convert List of lists to List of Sets
- Convert a list of multiple integers into a single integer in Python
