What is in index 0 of an R list if they usually start with index 1?

Coming from Python I try to get deeper into the habits and design principals of R. So this is not a homework question.

It seems usual that list() starting with index 1 and not 0.

> a = list(1,2,3)
> a[[1]]
[1] 1

But what is at index 0?

> a[[0]]
Error in a[[0]] : 
  attempt to select less than one element in get1index <real>
> a[0]

I know that there is a difference about [] and [[]]. I don’t fully understand the difference or the design principals behind it.

Is there an PEP equivalent for R to read about design decisions?

EDIT: The "duplicate" question doesn’t fit my question and there is also no accepted answer. The answers in my question IMHO are much better.

>Solution :

When you use [[]] you are extracting the element from the list. Therefore, you will have a[[1]] = 1, but an error for a[[0]]] because there is no such element.

When you use [] in a list you are slicing (sub-setting) it. That is why a[1] = [[1]] 1 and a[0] returns an empty element (there is no zeroth list).

This is made clear by checking the class of the outputs.

class(a[[1]]) # -> numeric
class(a[1]) # -> list

Leave a Reply