+ 1
Convert string to list in python3
x = 1,2,3,4,5 How to make list_x = [1,2,3,4,5] or tuple_x = (1,2,3,4,5). I make list_x = [x] but #output is: ['1,2,3,4,5']. So '1,2,3,4,5' is not interger. #edited#
5 Answers
+ 10
x = 1, 2, 3, 4, 5 is already a tuple. To turn it into a list use x = list(x).
If you're referring to a string x = '1, 2, 3, 4, 5', you can use something like x = list(map(int, x.split(',')))
x.split(',') turns the string into a list of strings, map() turns everything into integers, list() puts the items of the map object into a list
+ 6
x=1,2,3,4,5
l=[]
for i in x:
l.append(i)
print(l)
Thanks
0
When you convert a string into lists by using the list() function, you will get a list of each character from the string:
print(list("String"))
#Output: ["S", "t", "r", "i", "n", "g"]
0
x=â1,2,3,4,5â
l=[]
for i in range(len(x)):
if not(x[i]==â,â):
l.append(x[i])
- 1
instead of
list_x = [x]
use list comprehensions
list_x = [i for i in x]