To convert each list item from a string to an integer, use the map function.,A function. In this case the function will be the int function.,You do this by using the built-in list() function and passing the given string as the argument to the function.,Using another example from the section above, you can combine a separator with maxsplit to make a targeted conversion of a string to a list:
A string is surrounded by either single or double quotation marks:
# all the following are strings # a string enclosed in single quotes first_name = 'John' #a string enclosed in double quotes last_name = "Doe"
If you want to create a string that spans multiple lines, or what is known as a multiline string, use triple quotes to start and end it:
# a multiline string enclosed in triple quotes phrase = '' 'I am learning Python and I really enjoy learning the language! '' '
For example, if you tried to change the first letter of a word from lowercase to uppercase, you would get an error in your code:
#try and change lowercase 'p'
to uppercase 'P'
fave_language = "python"
fave_language[0] = "P"
print(fave_language)
#the output will be an error message
#fave_language[0] = "P"
#TypeError: 'str'
object does not support item assignment
A list can contain any of Python's built-in data types.
# a list of numbers my_numbers_list = [10, 20, 30, 40, 50] print(my_numbers_list) #output #[10, 20, 30, 40, 50]
You can change list items after the list has been created. This means that you can modify existing items, add new items, or delete items at any time during the life of the program.
programming_languages = ["Javascript", "Python", "Java"]
#update the 1 st item in the list
programming_languages[0] = "JavaScript"
print(programming_languages)
#output
#['JavaScript', 'Python', 'Java']
Last Updated : 10 Aug, 2022
Output:
Modified list is: [1, -4, 3, -6, 7]
Given:
xs = ['1', '2', '3']
Use map
then list
to obtain a list of integers:
list(map(int, xs))
In Python 2, list
was unnecessary since map
returned a list:
map(int, xs)
Use a list comprehension on the list xs
:
[int(x) for x in xs]
e.g.
>>> xs = ["1", "2", "3"] >>>
[int(x) for x in xs]
[1, 2, 3]
Just do,
result = [int(item) for item in result] print(result)
It'll give you output like
[1, 2, 3]
So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with errorhandling:
def maybeMakeNumber(s): "" "Returns a string 's' into a integer if possible, a float if needed or returns it as is. "" " # handle None, "", 0 if not s: return s try: f = float(s) i = int(f) return i if f == i else f except ValueError: return s data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"] converted = list(map(maybeMakeNumber, data)) print(converted)
Output:
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
To also handle iterables inside iterables you can use this helper:
from collections.abc import Iterable, Mapping def convertEr(iterab): "" "Tries to convert an iterable to list of floats, ints or the original thing from the iterable.Converts any iterable(tuple, set, ...) to itself in output. Does not work for Mappings - you would need to check abc.Mapping and handle things like { 1: 42, "1": 84 } when converting them - so they come out as is. "" " if isinstance(iterab, str): return maybeMakeNumber(iterab) if isinstance(iterab, Mapping): return iterab if isinstance(iterab, Iterable): return iterab.__class__(convertEr(p) for p in iterab) data = ["unkind", { 1: 3, "1": 42 }, "data", "42", 98, "47.11", "of mixed", ("0", "8", { "15", "things" }, "3.141"), "types" ] converted = convertEr(data) print(converted)
In Python 2.x you can use the map function:
>>> results = ['1', '2', '3'] >>>
results = map(int, results) >>>
results[1, 2, 3]
In Python 3.x you can use the same map
>>> results = ['1', '2', '3'] >>>
results = list(map(int, results)) >>>
results[1, 2, 3]
The third method which is common for both python 2.x and python 3.x i.e List Comprehensions
>>> results = ['1', '2', '3'] >>>
results = [int(i) for i in results] >>>
results[1, 2, 3]
A little bit more expanded than list comprehension but likewise useful:
def str_list_to_int_list(str_list):
n = 0
while n < len(str_list):
str_list[n] = int(str_list[n])
n += 1
return (str_list)
e.g.
>>> results = ["1", "2", "3"] >>>
str_list_to_int_list(results)[1, 2, 3]
Also:
def str_list_to_int_list(str_list):
int_list = [int(n) for n in str_list]
return int_list
The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings]. It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function. ,You can also use the eval() function in a list comprehension to convert a list of strings to a list of ints: ,This article shows you the simplest ways to convert a one-dimensional list consisting only of strings to a list of ints.,Of course, you can also convert a list of strings to a list of ints using a simple for loop. This is what most people coming from a programming language such as Java and C++ would do as they don’t know the most Pythonic way of using list comprehension, yet (see Method 1).
Suppose we have a list:
a = ["1", "2", "-3"]
Now, check the type of the first list element:
print(type(a[0]))
# <class 'str'>
Let’s apply the built-in function int()
, and get a list of integers using list comprehension:
a = ["1", "2", "-3"]
print([int(x) for x in a])
#[1, 2, -3]
Apply to the same list a
the following code:
a = ["1", "2", "-3"]
print(list(map(int, a)))
#[1, 2, -3]
Of course, you can also convert a list of strings to a list of ints using a simple for loop. This is what most people coming from a programming language such as Java and C++ would do as they don’t know the most Pythonic way of using list comprehension, yet (see Method 1).
a = ["1", "2", "-3"]
ints = []
for element in a:
ints.append(int(element))
print(ints)
#[1, 2, -3]
Last updated: Jun 16, 2022
Copied!my_list = ['10', '20', '30', '40'] new_list = [int(item) for item in my_list] print(new_list) #👉️[10, 20, 30, 40]
Copied!my_list = ['10', '20', '30', '40'] new_list = list(map(int, my_list)) print(new_list) #👉️[10, 20, 30, 40]
Copied!my_list = ['10', '20', '30', '40'] for index, item in enumerate(my_list): my_list[index] = int(item) print(my_list) #👉️[10, 20, 30, 40]
Author: Aditya Raj Last Updated: April 1, 2022
myList = ["1", "2", "3", "4", "5"]
output_list = []
for element in myList:
value = int(element)
output_list.append(value)
print("The input list is:", myList)
print("The output list is:", output_list)
Output:
The input list is: ['1', '2', '3', '4', '5']
The output list is: [1, 2, 3, 4, 5]
If there are elements in the list that cannot be converted to an integer, the program will run into the ValueError
exception as shown below.
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = []
for element in myList:
value = int(element)
output_list.append(value)
print("The input list is:", myList)
print("The output list is:", output_list)
Instead of the for loop, we can use list comprehension and the int()
function to convert a list to strings to a list of integers as follows.
myList = ["1", "2", "3", "4", "5"]
output_list = [int(element) for element in myList]
print("The input list is:", myList)
print("The output list is:", output_list)
Using the list comprehension has a restriction that we won’t be able to handle errors if any element of the input list is not converted to an integer because we cannot use exception handling inside the list comprehension syntax.
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = [int(element) for element in myList]
print("The input list is:", myList)
print("The output list is:", output_list)