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

4
  • 5
    what must be done for "test" ? bypass ? Commented Jun 19, 2020 at 16:07
  • 3
    Getting errors with what? Give a minimal reproducible example. Are you filtering the non-numerical values? Commented Jun 19, 2020 at 16:07
  • 1
    This is a duplicate of How to convert list of intable strings to int Commented Jun 19, 2020 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). Commented May 18, 2023 at 19:49

8 Answers 8

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]
Sign up to request clarification or add additional context in comments.

Comments

2

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']]

Comments

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]
>>> 

9 Comments

Bare except: is rarely a good idea.
@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 ^^
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 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)?
@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.
|
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)

Comments

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")

Comments

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

Comments

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)

Comments

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]

1 Comment

I would guess the output to this is not what the OP expects, '-2'.isdigit() is False.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.