0

I have about a hundred numbers contained as strings in a list, and I need to add all of them together. To do this, I'm using the following code -

for item in listo:
    sumo += int(item)

I'm getting a ValueError that says:

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

I don't know what causes this particular error, rather than just the error that says that the string couldn't be converted to an int. Does anyone know what the problem is, and how to fix it?

EDIT - I found the error! I used the .split() method, and I accidentally added one too many period, creating an empty string.

4
  • 2
    At least one item is an empty string. Commented Jun 21, 2017 at 23:12
  • I would guess what's happening is you're reading the list from a file, and the last entry is an empty line. Can you post a complete example that demonstrates the problem? Commented Jun 21, 2017 at 23:13
  • It indeed is! I used the split() method, and accidentally split it one time too many. Thanks for your help! Commented Jun 21, 2017 at 23:14
  • Note that you can use the sum(..) builtin with a generator, making it more declarative and a one-liner. Commented Jun 21, 2017 at 23:18

2 Answers 2

1

Type casting as intcan only be used if the passed string is valid. For eg. int('5') is valid but int('apple') is not.

The error is kind of self explanatory. The the parameter supplied to convert it to an integer is invalid. IF it was particular string it would have displayed that. Blank quotes would generally mean its an empty string you are trying to convert. It s good you have found the error yourself. generally the description of the error is a good pointer to what is wrong.

Good luck

Sign up to request clarification or add additional context in comments.

Comments

0
new_list = filter(None, list)
lisSum = sum(map(int,new_list ))

hope this is what your expecting

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.