2
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.

codeforester
  • 39,467
  • 16
  • 112
  • 140
soubhagya
  • 788
  • 2
  • 12
  • 37

6 Answers6

4

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(',')])
Kian
  • 1,319
  • 1
  • 13
  • 23
3

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]
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
3

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)
iBug
  • 35,554
  • 7
  • 89
  • 134
2

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]
atiq1589
  • 2,227
  • 1
  • 16
  • 24
1

You can also use map like this:

list(map(int,[i for i in l if i.isdigit()]))
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

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

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

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

Frost
  • 174
  • 1
  • 5
  • 13