1

I have a list of integers:

lists = [8,7,2]

I want it to be:

result = 872

I can do it in the following way:

result = 0
for count, i in enumerate(reversed(lists)):
    result += i*(10**count)

It works. but I think there should be another better and faster way. Thanks in advance

4 Answers 4

5

you can try this

int("".join(list(map(str,lists))))

map all the integers to strings then join them and conver them back to integer.

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

1 Comment

int("".join(map (str, lists)))
4

You can also do

from functools import reduce
reduce(lambda x,y: 10*x+y, (lists))

No need to convert to string and back.

(for the completeness sake) When list might contain numbers bigger than 9 you can do something more complicated but faster than converting to strings.

from functools import reduce
def combine(x,y):
    temp =y
    if (temp==0): 
        return x*10
    while(temp>0):
        x*=10
        temp//=10
    return x + y

reduce(combine,lists)

7 Comments

Thanks a lot. I think it's much better way
But it has limitation. If the length of list exceeds 9, it won't work
You mean if the number in list exceeds 9 ? right? I wasn't expecting that looking at the code you have provided in the question.
Sorry, I was my fault, I didn't tell you this. But what you did, excellent. Someone might get help from your answer
Thanks @RafeeMuhammad for pointing out. I have updated. of course it doesn't look as neat but it sure is faster :)
|
3

You could also just skin the string:

lists=[8, 7, 2]
result = int((str(lists)).strip("[]").replace(", ",""))

1 Comment

I'd been bashing my head, trying to figure out why a single list item of [1] would not convert to a string then int... has to do with the brackets! I'd vote this answer up a dozen times if I could.
1

Here is another simple way to do it using int, str and list comprehension.

lists = [8,7,2]
result = int("".join([str(l) for l in lists]))

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.