Extending lists
In Python you can extend lists using the addition sign or the extend function.
a = [1, 2]
b = [3, 4]
a = a + b
print('a1', a)
a.extend(b)
print('a2', a)
b = b.extend(b)
print('b1', b)
Output
a1 [1, 2, 3, 4]
a2 [1, 2, 3, 4, 3, 4]
b1 None
For PsychoJS this code is auto translated to:
a = [1, 2];
b = [3, 4];
a = (a + b);
console.log("a1", a);
a.concat(b);
console.log("a2", a);
b = b.concat(b);
console.log("b1", b);
Output
a1 1,23,4
a2 1,23,4
b1 [3, 4, 3, 4]
Two things are going wrong here.
- a + b is concatenating the two lists as strings.
- a.concat(b); doesn’t alter list a
As per Wakefield's Daily Tips - #27 by wakecarter, here is a custom function for joining two lists.
Python
def concat(a, b):
return a + b
JavaScript
function concat(a, b) {
return a.concat(b);
}
Then in your code component, write c = concat(a, b)
instead of c = a + b
.
This could be exended to three (or more) lists using a+b+c+etc. and a.concat(b, c, etc.) in the function. If would also be possible to set up a more complex function which checks the number of arguments, but unless you are regularly concatenating a chain of lists, it would probably be easier to just call the simple function more than once.