2

How do I access an item in a list of lists in GEE?

I know that using the method get() returns the element at the specified position in list. But the result of list.get(0) is [1, 2, 3], and I want the first element of each list in the list.

var list = ee.List([
  [1, 2, 3],
  [2, 4, 5],
  [3, 4, 5]
]);
5

Usually when you want to do something with each item in a list, you use map. In this case since you want the first element, you put .get(0) inside the map function.

var list = ee.List([[1, 2, 3], [10, 20, 30], [100, 200, 300]]);

print(list.map(function (innerList) {
  return ee.List(innerList).get(0);
}));

// Prints: [1,10,100]

This example contains ee.List(innerList).get(0) instead of innerList.get(0) because the map doesn't know that every element of list is a list — this cast is necessary in most cases when you map over a list to specify the expected type so you can call .get or other specific method on it.

2
  • Thanks, Kevin for your help. I'm trying to calculate precipitation accumulation. I have created a function whose entry is a list of lists that contain the year, start_day and end_day. To apply this function over the list, I used .map as you comment before. But I am finding different errors: The first one is .map is not a function and when I try to fix it I find another error of Invalid type. This is the link to my code: code.earthengine.google.com/7460981e0f6e7c99e4c36f0507383cfa Thanks in advance for your help. Aug 14 '20 at 9:14
  • 2
    @NataliaQuintero As I wrote in my answer, you must use ee.List to cast the element inside of the mapping function. In that case, you can do it by adding list_of_sequence = ee.List(list_of_sequence); as the first line of the function cumPr_of_each_year.
    – Kevin Reid
    Aug 14 '20 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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