Lists
# python
shopping = ["pear", 2, 3.1459]
print(shopping)
# indices select list element and start with 0
## ['pear', 2, 3.1459]
print(shopping[1])
## 2
# R
shopping <- list("pear", 2, 3.1459)
str(shopping)
## List of 3
## $ : chr "pear"
## $ : num 2
## $ : num 3.15
# indices select sub list and start with 1
str(shopping[1])
## List of 1
## $ : chr "pear"
str(shopping[[1]]) # use [[]] to select list element
## chr "pear"
Modifying Lists
# python
shopping.append("honey")
shopping += ["sour cream"] # quick syntax for append
shopping[1] = [1, 2, 3]
print(shopping)
## ['pear', [1, 2, 3], 3.1459, 'honey', 'sour cream']
# R
shopping <- c(shopping, list("honey", "sour cream"))
shopping[2] <- list(1:3)
shopping[[2]] <- 1:3 # same as above
str(shopping)
## List of 5
## $ : chr "pear"
## $ : int [1:3] 1 2 3
## $ : num 3.15
## $ : chr "honey"
## $ : chr "sour cream"
Tuples
# tuple
mytup = (1, 2., "3")
print(mytup)
# tuples cannot be changed
## (1, 2.0, '3')
try:
mytup[0] = 5
except:
print("Unexpected error:", sys.exc_info()[1])
## Unexpected error: 'tuple' object does not support item assignment
# R - tuples do not exist, the one created in python is simply a regular list
str(py$mytup)
## List of 3
## $ : int 1
## $ : num 2
## $ : chr "3"
Dictionaries (named lists)
# python
dict = {"spoons" : 5, "frog" : "green"}
print(dict)
## {'spoons': 5, 'frog': 'green'}
print(type(dict))
## <class 'dict'>
print(dict["frog"]) # select list element by name
## green
dict["gravity"] = 9.81 # re-assign list element by name
print(dict.keys()) # print all keys
## dict_keys(['spoons', 'frog', 'gravity'])
print(dict.values()) # print all values
## dict_values([5, 'green', 9.81])
# R - dictionaries don't exist separately, the one created in pythin is simply a named list
str(py$dict)
## List of 3
## $ spoons : int 5
## $ frog : chr "green"
## $ gravity: num 9.81
dict <- list("spoons" = 5, "frog" = "green", "no name") # mixed named and unnamed lists supported
str(dict)
## List of 3
## $ spoons: num 5
## $ frog : chr "green"
## $ : chr "no name"
dict$gravity <- 9.81 # modify by name
str(dict[[1]]) # select by index
## num 5
str(dict$spoons) # or by name
## num 5
str(names(dict)) # print all keys (names)
## chr [1:4] "spoons" "frog" "" "gravity"
str(unname(dict)) # remove names to get values only
## List of 4
## $ : num 5
## $ : chr "green"
## $ : chr "no name"
## $ : num 9.81