Python - Integers String to Integer List
In this article, we will check How we can Convert an Integer String to an Integer List
Using split()
and map()
Using split()
and map()
will allow us to split a string into individual elements and then apply a function to each element.
s = "1 2 3 4 5"
# Convert the string to a list of integers using split and map
int_list = list(map(int, s.split()))
print(int_list)
Output
[1, 2, 3, 4, 5]
Explanation
- The
split()
method splits the input strings
into individual string elements based on spaces. - The
map(int, s.split())
applies theint
function to each element, converting them to integers, andlist()
collects the results into a list, which is then printed as[1, 2, 3, 4, 5]
.
Using List Comprehension
Using list comprehension allows you to create a new list by applying an expression to each element of an iterable. This method is compact and often more readable than traditional loops, making it ideal for transforming or filtering elements of a list or string.
# Input string of integers
s = "1 2 3 4 5"
# Convert the string to a list of integers using list comprehension
int_list = [int(i) for i in s.split()]
# Print the result
print(int_list)
Output
[1, 2, 3, 4, 5]
Explanation
s.split()
method splits the input strings
into individual string elements, and the list comprehension[int(i) for i in s.split()]
converts each element to an integer.- The resulting list of integers
[1, 2, 3, 4, 5]
is stored inint_list
and printed.
Using split()
and a for
Loop
Using split()
and a for loop together allows you to split a string into individual elements and then iterate through each element to apply a specific operation, such as converting each element to an integer.
s = "1 2 3 4 5"
# Initialize an empty list
int_list = []
# Split the string and iterate over the parts
for num in s.split():
int_list.append(int(num))
# Print the result
print(int_list)
Output
[1, 2, 3, 4, 5]
Explanation
- The
s.split()
method splits the input strings
into individual string elements, and the for loop iterates through each element. - Inside the loop,
int(num)
converts each string element to an integer, which is then appended to theint_list
, resulting in[1, 2, 3, 4, 5]
.