I'm trying to convert a list to a single integer using two methods:
for
loop works fine and gives me the integer
>>> a_list = "123456789"
>>> a_list = list(a_list)
>>> b_int = ""
>>> for num in a_list:
... b_int = num
...
>>> print(int(b_int))
123456789
however join()
returns a ValueError
>>> a_list = "123456789"
>>> c_int = ""
>>> c_int.join(a_list)
>>> print(int(c_int))
Traceback (most recent call last):
File "xxx.py", line 4, in <module>
print(int(c_int))
^^^^^^^^^^
ValueError: invalid literal for int() with base 10: ''
Why does join()
returns a ValueError? It was suggested in a number of different posts as a better solution.
CodePudding user response:
As the string is a string it cannot be "joined" to a number, but if the string contains numbers it can be cast to numbers and then reduced
list("123456789")
Out[6]: ['1', '2', '3', '4', '5', '6', '7', '8', '9']
[int(x) for x in list("123456789")]
Out[7]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
sum([int(x) for x in list("123456789")])
Out[8]: 45
CodePudding user response:
The origin of the ValueError
is that you are calling int
to an empty string and not to the join
one. String are immutables so you need always to re-assign the result.
a_list = "123456789"
c_int = ""
c_int = c_int.join(a_list) # <-
print(int(c_int))
By the way int(a_list)
does the same.