How to convert element of a list into a single number

Viewed 236

I have list of integers List<int> = [1,2,3,5] I want to convert it into a single number like 1235. How can I do this using loops?

5 Answers

Loops are unnecessary if you use join:

int.tryParse(list.join());
int parsed = int.tryParse(list.join()); //concatenate list elements without delimiter

If you want to sum up elements in list:

final list = [2,4,242];
int sum = list.reduce((value, element) => value + element);
print(sum);//248

Not only sum up, even can concatenate elements using reduce:

int concat = list.reduce((value, element) => int.tryParse("$value$element"));
print(concat); // 24242
List<int>  lst = [1,2,3,5];
String s ='';
lst.forEach((element) { 
      s = s + element.toString();
});
int y = int.tryParse(s);
print(y);


A forEach loop should do this pretty easily for you.

String str = '';
List<int> list = [1,2,3,4,5];
list.forEach((element) => str += element.toString());

The function in the forEach will take each element in the list and perform the function on it. Documentation

You can use map() function over list elements:

# initial list
my_list = ['1', 2, '3', 5]

# convert list to string
simple_text=''.join(map(str, my_list))
print('result: '+simple_text)

And here is return:

result: 1235
Related