Joining elements in a list without the join command
Solution 1:
If you just want to print the number rather than return
an actual int
:
>>> a = [12,4,15,11]
>>> print(*a, sep='')
1241511
Solution 2:
You could just convert each element to a string
, add them, and then convert back to an int
:
def lists(list1):
answer=''
for number in list1:
answer+=str(number)
print(int(answer))
lists([12,4,15,11])
>>>
1241511
Solution 3:
s = ""
for x in map(str, x):
s += x
print(s)
1241511
Solution 4:
There can be few more options like
Option1
>>> lst=[12,4,15,11]
>>> str(lst).translate(None, '[,] ')
'1241511'
Option 2
>>> join = lambda e: str(e[0]) + join(e[1:]) if e else ""
>>> join(lst)
'1241511'
Option 3
>>> ("{}"*len(lst)).format(*lst)
'1241511'
Option 4
>>> reduce(lambda a,b:a+b,map(str,lst))
'1241511'
Solution 5:
a numeric solution, using your code
import math
def numdig(n):
#only positive numbers
if n > 0:
return int(math.log10(n))+1
else:
return 1
def lists(list1):
answer = 0
h = 0
while list1 != []:
answer = answer * 10 ** h + list1[0]
list1.pop(0)
if list1 != []:
h = numdig(list1[0])
print(answer)
lists([12,4,15,11])