1

I want to set multiple values in a list in GEE. I wanted to use ee.List.set() but that only accepts integers as inputs and not lists. So I tried to build a function that does that but it still isn't working. See code below. Important to know is that the length of list2 is variable, but of course smaller than the length of list1. What would be a good solution? The goal is to get list3 = [0, 1, 0, 1, 0] as output.

var n = 5; // is arbitrary
var list1 = ee.List.repeat(0, n);
var list2 = ee.List([1, 3]); // the length of this list is variable (length m, with m < n), 
// and the values in this list are arbitrary integers neq 0. 

var list3 = list1.set(list2, 1); // This does not work since .set() only accepts an integer, not a list as first input.
print(list3)

// So I tried using a function

var setValue = function(number){
  return list1.set(number, 1);
};
var list3 = list2.map(setValue);
print(list3)
// but this does not return a single list, but m separate lists. 

2 Answers 2

3

If the range you're trying to set is contiguous, then you can just use List.splice(). Your code doesn't work as you're hoping because mapping over list2 is just going to return another list the size of list2. It doesn't (and cant) actually modify list1.

If you really have a list of random indexes that you want to replace, you need to map over a sequence from 0 to list1.length, and for each index, see if it's in list2.

result = ee.List.sequence(0, list1.size()).map(function(index) {
    return ee.Algorithms.If(list2.contains(index), newval, list1.get(index))
})
2

I don't know which is your final goal but, your affirmation of ee.List.set() only accepts integers as inputs and not lists is not true because you inverted arguments in 'set' method. Following code works without any error.

var n = 5; // is arbitrary
var list1 = ee.List.repeat(0, n);
var list2 = ee.List([1, 3]); // the length of this list is variable (length m, with m < n), 
// and the values in this list are arbitrary integers neq 0. 

var list3 = list1.set(1, list2); // This works because .set() you inverted argumets.
print(list3);

// So I tried using a function

var setValue = function(number){
  return list1.set(number, 1);
};
var list3 = list2.map(setValue);
print(list3);
// but this does not return a single list, but m separate lists. 

Result is as follows after running above code in GEE code editor:

enter image description here

1
  • Thanks for your answer but my goal is to get list3 = [0, 1, 0, 1, 0] Nov 25, 2021 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.