Can anyone explain why list1
and list2
below are not identical?
list1 <- list()
lev1 <- "level1"
lev2 <- "level2"
list1[[lev1]][[lev2]] <- 1
list1
$level1
level2
1
list2 <- list()
list2$level1$level2 <- 1
list2
$level1
$level1$level2
[1] 1
Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.
- Python arrays & list items can be accessed with positive or negative numbers (also known as index). - For instance our array/list is of size n, then for positive index 0 is the first index, 1 second, last index will be n-1.
The star(*) operator unpacks the sequence/collection into positional arguments. So if you have a list and want to pass the items of that list as arguments for each position as they are there in the list, instead of indexing each element individually, you could just use the * operator.
What are Indexing and Slicing? Indexing: Indexing is used to obtain individual elements. Slicing: Slicing is used to obtain a sequence of elements. Indexing and Slicing can be be done in Python Sequences types like list, string, tuple, range objects.
This is occurring because you are assigning a length 1 vector to a NULL atomic vector.
From help(Extract)
-
When
$<-
is applied to a NULLx
, it first coercesx
tolist()
. This is what also happens with[[<-
if the replacement valuevalue
is of length greater than one: ifvalue
has length 1 or 0,x
is first coerced to a zero-length vector of the type ofvalue
.
Change the assignment to ... <- 1:2
(or something other than a length 0 or 1 vector) and you will get the same result in both code blocks.
list1 <- list()
lev1 <- "level1"
lev2 <- "level2"
list1[[lev1]][[lev2]] <- 1:2
list1
# $level1
# $level1$level2
# [1] 1 2
list2 <- list()
list2$level1$level2 <- 1:2
list2
# $level1
# $level1$level2
# [1] 1 2
A simpler example of this, as mentioned by @alexis_laz in the comments, is just to begin with a NULL atomic vector and look at what happens.
x <- NULL
## assign a length 1 vector --> atomic result
x[["lev1"]] <- 1
x
# lev1
# 1
y <- NULL
## assign a length > 1 vector --> list result
y[["lev1"]] <- 1:2
y
# $lev1
# [1] 1 2
The result from $<-
is always a list so I have omitted it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With