Conditional logic for checking if true and placing it in an array

I am not sure why I am getting this wrong. Trying to create a list of numbers that checks true iterating over a list.

(
var lista;
lista = [];
40.do { |n|
    n.postln;
    if (n % 4 == 0) {
        lista.addAll(n);
    };
};
lista.postln; // This will post the complete list to the post window
)

When you define an empty array, it has a maximum size of 2. Array max sizes are always a power of two, the tricks is to reassign the result of adding to the array so you don’t have to worry about the max size:

(
var lista;
lista = [];
40.do { |n|
    n.postln;
    if (n % 4 == 0) {
        lista = lista.add(n);
    };
};
lista.postln; // This will post the complete list to the post window
)

You can also use a List which does not have a max size at the expense of slightly slower performance, nothing that would matter in this case.

(
var lista;
lista = List.new;
40.do { |n|
    n.postln;
    if (n % 4 == 0) {
        lista.add(n);
    };
};
lista.postln; // This will post the complete list to the post window
)

Forgot that detail! Many thanks!

You might also try

(..40).select{|x| x % 4 == 0 }
1 Like