0

I have list that contains only integers. I want it to be a full single integer. Such that I have list like this:

[500, 400, 300, 200, 100]

I want it to be like this:

500400300200100

Where is what I have tried:

ls = [500, 400, 300, 200, 100]
new_ls = []
for i in range(len(ls)):
    new_ls.append(str(ls[i]))

integer = int(''.join(new_ls))
print(integer)

Note that: join() doesn't work for list which contains integer(at least this is what I know). For that I am first turning the list to string then joining. Is there any shorter way for this?

martineau
  • 119,623
  • 25
  • 170
  • 301
Saykat
  • 124
  • 2
  • 12

2 Answers2

2

You could do:

lst = [500, 400, 300, 200, 100]
result = int(''.join(list(map(str, lst))))
print(result)

Output

500400300200100
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
2

Try:

integer = int(''.join([str(x) for x in ls]))
luigigi
  • 4,146
  • 1
  • 13
  • 30
  • You don't need to create a temporary list: `integer = int(''.join(str(x) for x in ls))` would work just fine. This is called a [generator expression](https://docs.python.org/3/reference/expressions.html#generator-expressions). – martineau Oct 24 '19 at 11:22
  • @martineau Thanks for the hint. But I dont see the advantage of a generator in this example. Can you give some short explanation to this? – luigigi Oct 24 '19 at 11:39
  • @martineau AFAIK, `str.join` is [one of the few exceptions where making a container is actually better than genexp](https://stackoverflow.com/questions/37782066/list-vs-generator-comprehension-speed-with-join-function) – Chris Oct 24 '19 at 11:42
  • It avoids creating a temporary list whose only purpose is to be passed to `join()` as an argument. If `ls` is short it probably doesn't make much difference (unless it done millions of times). – martineau Oct 24 '19 at 11:42
  • @Chris: That may not apply in this case because `str()` has to be called either way. The only definitive test would be to `timeit`. – martineau Oct 24 '19 at 11:47