-1
list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']

I've a list containing 10 items. How to convert this into a list of integers? I'm getting errors because of 'test' in the list.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Joe
  • 57
  • 1
  • 9
  • 5
    what must be done for "test" ? bypass ? – bruno Jun 19 '20 at 16:07
  • 3
    Getting errors with what? Give a [mre]. Are you *filtering* the non-numerical values? – jonrsharpe Jun 19 '20 at 16:07
  • 1
    This is a duplicate of [How to convert list of intable strings to int](https://stackoverflow.com/questions/9869524/how-to-convert-list-of-intable-strings-to-int) – Trenton McKinney Jun 19 '20 at 16:56
  • There are two underlying questions here: how to apply the logic to each element of the list (which presumably you can already do), and how to check whether a given element represents an integer. Given the latter, it's trivial to make a function that gives you an integer when possible, and the original value otherwise; then that can be applied to each element. Every approach either boils down to that, or filtering out the non-integers (if you don't want them in the result). – Karl Knechtel May 18 '23 at 19:49

8 Answers8

2

Don't call a list literally list. (It shadows the builtin list function and may give you weird bugs later!)

Assuming you just want to disregard non-numeric values, you can do this in a comprehension by using a filter at the end:

>>> [int(x) for x in [
...     '5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test'
... ] if x.lstrip('-').isdigit()]
[5, 12, 4, 3, 5, 14, 16, -2, 4]
Samwise
  • 68,105
  • 3
  • 30
  • 44
1
list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']

new_list = []
for i in list:
    try:
        new_list.append(int(i))
    except ValueError:
        print("String found")
Erica
  • 2,399
  • 5
  • 26
  • 34
Clifton
  • 23
  • 2
1

supposing you want to forget wrong values, what about

list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
list2 = []
for _ in list:
    try:
        list2.append(int(_))
    except:
        pass

print(list2)

execution :

>>> list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
>>> list2 = []
>>> for _ in list:
...     try:
...         list2.append(int(_))
...     except:
...         pass
... 
>>> print(list2)
[5, 12, 4, 3, 5, 14, 16, -2, 4]
>>> 
bruno
  • 32,421
  • 7
  • 25
  • 37
  • Bare `except:` is rarely a good idea. – jonrsharpe Jun 19 '20 at 17:23
  • @jonrsharpe yes but as I say at the beginning of my answer `supposing you want to forget wrong values`, of course if the goal is different the implementation must be too ^^ – bruno Jun 19 '20 at 17:28
  • Right, but that still doesn't imply the use of `except:`. At the absolute minimum `except Exception:`, but the name of the appropriate error is right in what you've written. – jonrsharpe Jun 19 '20 at 17:30
  • @jonrsharpe that time I am not sure to understand what you mean, do you mean to indicate I have an exception doing the `append()` (but `int(_)` is ok)? – bruno Jun 19 '20 at 17:33
  • No, I mean the appropriate error is in *"forget wrong values"* - `ValueError`. – jonrsharpe Jun 19 '20 at 17:44
  • @jonrsharpe just means that you should never use an bare `except` because it will catch all exceptions, especially those that are unexpected. This is considered and anti-pattern. When using `except`, it should always include only the actual exception you're catching. [The Most Diabolical Python Antipattern](https://realpython.com/the-most-diabolical-python-antipattern/) – Trenton McKinney Jun 19 '20 at 21:19
  • @TrentonMcKinney thank you for your remark. I will explain more : If I want to catch `int('aze')` I can use `except ValueError: ...`, but in case the 'wrong' element is not a string but the instance of a class, it is possible for that class to define a conversion method called by `int(the_instance)` ? If yes that method can produces any exception including a BaseException, and to catch it I need `except:` or `except BaseException:`. A wrong list can contain anything not only 'test'. May be what I say is stupid, but I mainly write in C++ and in C++ we can redefine operators including conversion – bruno Jun 19 '20 at 21:33
  • _but in case the 'wrong' element is not a string but the instance of a class,_ this is the point of not having bare exceptions. In the case you outline, that exception should be allowed to happen, because it is not expected and means there is some different issue. It's probably a much different mindset compared to C++. – Trenton McKinney Jun 19 '20 at 21:40
  • 1
    @TrentonMcKinney in a 'normal' case yes because that hides bug, but my answer starts by `supposing you want to forget wrong values` so even that case must be silently hidden. – bruno Jun 19 '20 at 21:41
1

Keep all values in the list:

t = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']

t = [int(v) if v.lstrip('-').isnumeric() else v for v in t]

print(t)

# output
[5, 12, 4, 3, 5, 14, 16, -2, 4, 'test']

Remove non-numeric values:

t = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']

t = [int(v) for v in t if v.lstrip('-').isnumeric()]

print(t)

# output
[5, 12, 4, 3, 5, 14, 16, -2, 4]

Nested lists:

t = [['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test'] for _ in range(3)]

t = [[int(v) if v.lstrip('-').isnumeric() else v for v in x] for x in t]

print(t)

# output
[[5, 12, 4, 3, 5, 14, 16, -2, 4, 'test'],
 [5, 12, 4, 3, 5, 14, 16, -2, 4, 'test'],
 [5, 12, 4, 3, 5, 14, 16, -2, 4, 'test']]
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
1

Use int() to convert the strings and use .isnumeric() to make sure the string represents a number.

str_arr = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
int_arr = []

for s in str_arr:
    if s.strip('-').isnumeric():
        int_arr.append(int(s))

print(int_arr)
AJ_
  • 1,455
  • 8
  • 10
0

Use the following code:

list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']

print([int(i) for i in list if i.lstrip('+-').isdigit()])

Which will give the following output:

[5, 12, 4, 3, 5, 14, 16, -2, 4]
Run_Script
  • 2,487
  • 2
  • 15
  • 30
0

You are getting error because alphabets cannot be converted to integers. However integers maybe converted to strings.

You may solve you issue by using 'try' and 'except'

I will give you how it can be done

for i in range(len(list)):
    try:
        list[i] = int(list[i])
    except:
        print(i,'cannot be converted to string')

The try and except statements work just like if and else statements. If there is no error in the code then 'try' statement will work. Whenever there is an error, except statement will get into action.

You can imagine it as:

if (no_error):           #try statement
    do_these_things      
elif (any_error):        #except statement
    do_these_instead
Vijeth Rai
  • 321
  • 2
  • 10
0

Please try the following code:

list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
list1=[]
for i in list:
    if(i.isnumeric()==True):
        list1.append(i)
    else:
        continue
print(list1)
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158