0

I am having one array like below.

a = [1,2,3,4]

I want to make this array to single value like this:

a = [1234]

How can I do this in Python?

  • Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve). – vaultah Sep 27 '15 at 10:28
  • possible duplicate of [Joining List has integer values with python](http://stackoverflow.com/questions/3590165/joining-list-has-integer-values-with-python) – kRiZ Sep 27 '15 at 10:41

3 Answers3

3

You can use join to join all element in array, but you have to convert them to a string first:

>>> a = [1,2,3,4]
>>> [int(''.join([str(i) for i in a]))]
[1234]
ahmed
  • 5,430
  • 1
  • 20
  • 36
  • How are you using it? – ahmed Sep 27 '15 at 12:05
  • yes. got it. I have run it by program not in terminal. So it didn't returned anything. Now assigned it to a variable and print it and now i get the number. t = [int(''.join([str(i) for i in a]))] print t – Dinesh Khanna V Sep 27 '15 at 12:49
0

you can do it without converting each element to string.

>>> def sum_elements(arr):
...     s = 0
...     for e in arr:
...         s *= 10
...         s += e
...     return s
... 
>>> a = [1, 2, 3, 4]
>>> a = [sum_elements(a)]
>>> a
[1234]
>>>  
mohan3d
  • 225
  • 1
  • 3
  • 9
0

You can loop for all elements of a and add the digit multiplied by a power of 10 to reach the good value.

a = [1,2,3,4]
b = [0]
for i in xrange(len(a)):
    b[0]+= (10**(len(a)-i-1))*a[i]
print a, b

[1, 2, 3, 4] [1234]

Abdallah Sobehy
  • 2,881
  • 1
  • 15
  • 28