# Making a sublist from a list

• Python
Gold Member
Hello PF!

Initializing with an empty list [], how would we perform the operations [[1]] and then [[1,2]] then [[1,2,3]] then [[1,2,3],[2]] then [[1,2,3], [2,4]] then [[1,2,3],[2,4],[1]] and so on. I'm trying to do this iteratively, so within a for-loop. Basically, given a list of numbers [1,2,3,2,4,1] add them to a sublist until the sum of values of that sublist exceeds a threshold, in which case create a new sublist. I've no clue how to do this, and have googled but to no avail

## Answers and Replies

Gold Member
You didn't specified a language, but in PHP:

PHP:
<?php
function makeList($numbers,$threshold){
$list = [];$sublist = [];
$total = 0; foreach($numbers as $number){$sublist[] = $number;$total += $number; if($total > $threshold){$list[] = $sublist;$total = 0;
$sublist = []; } } if(!empty($sublist)){
$list[] =$sublist;
}

return $list; }$numbers = [1,2,3,2,4,1];
$threshold = 5; var_dump(makeList($numbers, \$threshold));

Output:

Code:
array(3) {
[0]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
[1]=>
array(2) {
[0]=>
int(2)
[1]=>
int(4)
}
[2]=>
array(1) {
[0]=>
int(1)
}
}

Mentor
You didn't specified a language
It's in the thread title -- Python.

jack action
Gold Member
It's in the thread title -- Python.
Then it will be left as an exercise for the OP to convert it!

jedishrfu
Mentor
Then it will be left as an exercise for the OP to convert it!
I wonder how many teachers have gotten that response from their students.

jack action
Gold Member
Got it, thanks for the suggestion!