Python Forum

Full Version: Incrementing binary number
You're currently viewing a stripped down version of our content. View the full version with proper formatting.


Hello, I got this assignment of incrementing a binary number (which displays as a string) without using base converting.

i wrote the code which i think is pretty good, but i got stuck with an error message when used this line of code:
return ''.join(lst_binary.insert(0,'1'))
that happens when the prog gets a string like '111', and needs to add another digit at the end of number.

the error i got was
Error:
"TypeError: can only join an iterable"
while was debugging with python-tutor

this is the whole code:
def inc(binary):
    lst_binary = list(binary)
    for bit in range(len(binary)-1, -1, -1):
        if lst_binary[bit] == '0':
            lst_binary[bit] = '1'
            return ''.join(lst_binary)
        else:
            lst_binary[bit] = '0'
    return ''.join(lst_binary.insert(0,'1'))
im not looking though for other ways to do this, just to understand why this line doesnt work
The method insert of lst_binary returns None. Just memorize, that methods which mutates the object, returns regularly None. Immutable objects return something, when you use a method. For example str.upper('Foo') returns a new object, because the object itself is not mutable. It's immutable.

Methods of lists like sort, insert and remove won't return the list itself. The list object is mutating.
Just do your modification to your list with insert and use return ''.join(lst_binary) to join the modified list.
(Nov-10-2017, 11:40 AM)DeaD_EyE Wrote: [ -> ]The method insert of lst_binary returns None. Just memorize, that methods which mutates the object, returns regularly None. Immutable objects return something, when you use a method. For example str.upper('Foo') returns a new object, because the object itself is not mutable. It's immutable.

Methods of lists like sort, insert and remove won't return the list itself. The list object is mutating.
Just do your modification to your list with insert and use return ''.join(lst_binary) to join the modified list.

Thanks for the reply. At last i thought about this way return '1' + ''.join(lst_binary), and it works as well.