0

Why am I getting this error?

ValueError: invalid literal for int() with base 10: 'ab'

It happens when try to change a string list into an int list.

x = [["a","b"], ["c"]]
y = []

for i in x:
    answer = ''.join(i)
    y.append(answer)

final_value = [int(n) for n in y] #the error comes from here
print(final_value)

What should I do in order to make it work?

5
  • You are trying to cast string values ("ab" and "c"), that are not integers, to an integer value and this will result in an error. What is your code supposed to do? Commented Dec 20, 2015 at 22:44
  • my bad, I thought I wrote 1,2 and 3, sorry. Commented Dec 20, 2015 at 22:47
  • 1
    What made you think "a" can be converted into an integer? Commented Dec 20, 2015 at 22:47
  • @ozgur Yeah checked for the code for 1 hour and didn't see that I wrote a, b and c instead of 1 2 and 3... Commented Dec 20, 2015 at 22:48
  • Happens to the best of us @Sia Commented Dec 21, 2015 at 2:52

1 Answer 1

1

You're getting this error because you're trying to pass the built-in int() function a string ("ab") that contains characters that cannot be converted to an integer. Out of curiosity what were you expecting int("ab") to return?

Converting a list of strings to a list of ints would work if all of your strings could be converted to integers like this:

x = [["1","11"], ["101"]]
y = []

for i in x:
    answer = ''.join(i)
    y.append(answer)

final_value = [int(n) for n in y] #the error comes from here
print(final_value)

This will print

[111, 101]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.