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.
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.
 
    
     
    
    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(',')])
 
    
    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]
 
    
    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)
 
    
    You can also use map like this:
list(map(int,[i for i in l if i.isdigit()]))
 
    
    Given: l='2,3,4,5,6'
Lazy way: output=eval('['+l+']')
Lazy way with Python 3.6+ (using fStrings): output=eval(f"[{l}]")
