Convert string of numbers to list of numbers

Question:

l='2,3,4,5,6'

expecting:

[2,3,4,5,6]

In python how can I convert into the above format

the first one is a string of some numbers I am expecting a list of same numbers.

Asked By: soubhagya

||

Answers:

You could use a list comprehension:

l='2,3,4,5,6'

result = [int(i) for i in l.split(',')]
print(result)

Output

[2, 3, 4, 5, 6]

The above is equivalent to the following for loop:

result = []
for i in l.split(','):
    result.append(i)

As an alternative you could use map:

l = '2,3,4,5,6'
result = list(map(int, l.split(',')))
print(result)

Output

[2, 3, 4, 5, 6]
Answered By: Dani Mesejo

Try this simple and direct way with a list comprehension.

list_of_numbers = [int(i) for i in l.split(",")]

Alternatively, you can fix up the string so it becomes a “list of strings”, and use literal_eval:

import ast
s = "[" + l + "]'
list_of_numbers = ast.literal_eval(s)
Answered By: iBug

As simple as this:

in Python2:

print [int(s) for s in l.split(',')]

and in Python3 simply wrapped with a parentheses:

print([int(s) for s in l.split(',')])
Answered By: Kian

you can use map and split to convert.

map(int, l.split(','))

Example:

l='2,3,4,5,6'
print(map(int, l.split(',')))

output

[2, 3, 4, 5, 6]
Answered By: atiq1589

You can also use map like this:

list(map(int,[i for i in l if i.isdigit()]))
Answered By: Mehrdad Pedramfar

Given: l='2,3,4,5,6'

Lazy way: output=eval('['+l+']')

Lazy way with Python 3.6+ (using fStrings): output=eval(f"[{l}]")

Answered By: Frost
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.