Removing the ' from a list when indexing it

71 Views Asked by At

I have a list of numbers which I have in the following way (numbers are only an example):

list = '1, 2, 3, 4, 5'

I need them in an index format, so I do the following:

format = [list]

I now get it the following way:

['1, 2, 3, 4, 5']

However, I need it this way:

[1, 2, 3, 4, 5]

Can you tell me how to do that?

Thank you so much in advance!

2

There are 2 best solutions below

2
On

Try the split function this way:

list1 = '1, 2, 3, 4, 5'

format1 = list(map(int, list1.split(', ')))

print(format1)

It will display :

[1, 2, 3, 4, 5]

PS : You should avoid having a variable called list. As it is a type of variable, it can cause serious issues

3
On

What you want to do is evaluate (eval) some code so it gets resolved by the interpreter. Since you cannot eval lists, you have to put the square brackets in the string, so it gets evaluated:

l = '[1, 2, 3, 4, 5]'
eval(l)
>>> [1, 2, 3, 4, 5]

Explanation:

Your first "list" is an object whose type is not a list, but a string (str).

list = '1, 2, 3, 4, 5'
type(list)
>>> str

By the way, I highly encourage you not to use python keywords such as 'list' as variable names

When you put square brackets around, you're defining a list with a single object, which is this string object:

format = [list]

type(format)
>>> list

len(format) # How many elements does it have?
>>> 1

So what you actually want to do is to define this list in a string manner and evaluate it:

l = '[1, 2, 3, 4, 5]'
eval(l)
>>> [1, 2, 3, 4, 5]