The insert function is returning None

Viewed 35

in python, I am trying to insert into a list recursively for a decimal to binary converter but the insert it is returning none

def dectob(num):
  print(num)
  if num==0:
    return []
  hnum = int(num/2)
  if num - hnum == hnum:
    asn="0"
  else:
    asn="1"
  return dectob(hnum).insert(0,asn)
print(int(''.join(dectob(6666)))==1101000001010)

asn: answer

num: base ten number

hnum: integer of half of num

I tried everything I made this longer version so it prints all the data

def dectob(num):
  print(num)
  if num==0:
    print("got")
    blanklist=[]
    print(blanklist)
    return blanklist
  hnum = int(num/2)
  if num - hnum == hnum:
    asn="0"
  else:
    asn="1"
  ret= dectob(hnum)
  print(ret)
  print(asn)
  return ret.insert(0,asn)
print(int(''.join(dectob(6666)))==1101000001010)
1 Answers

insert() modifies the list in place but does not return a value. Typically with functional programming you avoid side effects and treat most data structures as immutable, so insert() is probably the wrong choice here. Instead of mututaing the returned list, you can simply return the result of recursion along with the new value:

def dectob(num):
    if num==0:
        return []
    hnum = int(num/2)
    if num - hnum == hnum:
        asn="0"
    else:
        asn="1"
    return dectob(hnum) + [asn]

int(''.join(dectob(6666))) == 1101000001010
# True
Related