Mytsu
Mytsu

Reputation: 33

How can I make an integer from list of integers?

How can I make an integer from a list of integers? For example :from lst = [1, 2, 3] make a = 123? I tried that:

for i in lst:
    print(i, end = '')

but if I need don't print, but just to have this number?

Upvotes: 3

Views: 96

Answers (4)

CodeP
CodeP

Reputation: 254

You can use .join method to create a string and convert it to int like this:

a = int(''.join(str(x) for x in lst))

Cheers.

Upvotes: 1

jpp
jpp

Reputation: 164623

Using sum with a generator expression:

lst = [1, 2, 3]
n = len(lst)
res = sum(val * 10**(n-idx) for idx, val in enumerate(lst, 1))

This is, in effect, a more explicit representation of what int('123') should do internally.

Upvotes: 3

Learning is a mess
Learning is a mess

Reputation: 8277

You can use reduce (functools.reduce in Python3):

a = reduce( lambda x,y: 10*x + y, lst)

Upvotes: 3

Rakesh
Rakesh

Reputation: 82765

  • Use map to convert element in list to string
  • use str.join to concat the element in the list

Ex:

lst = [1, 2, 3]
print("".join(map(str, lst)))

If you need int object

Use:

print(int("".join(map(str, lst))))

Upvotes: 4

Related Questions