-2

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 Answers2

0

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

Clément Perroud
  • 483
  • 3
  • 12
  • i got this error on this code : `TypeError: 'str' object is not callable` – I'mahdi Aug 25 '21 at 13:02
  • @user 1740557 That is because you assigned a string value to `list`. That masks the real `list`, which is why you should not do that. – BoarGules Aug 25 '21 at 15:34
-1

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]
Iván Sánchez
  • 248
  • 1
  • 10
  • this is not answer, input like this : '1, 2, 3, 4, 5' `not '[1, 2, 3, 4, 5]'` – I'mahdi Aug 25 '21 at 13:05
  • @user1740577 The question looks formulated by someone who does not understand the basics of python, that's why I added the brackets to the string. I know it is not the input, but you can obviously add these with a simple function to the input, which I didn't add for simplicity – Iván Sánchez Aug 25 '21 at 14:14
  • i know, i understand what you say, i say only that this not input and I say as you know i don't downvote you, i don't downvote any body – I'mahdi Aug 25 '21 at 14:16