library(reticulate) # to use python in RStudio
library(tidyverse) # data wrangling and plotting with R
In this note, R code chunks are in light pink, while python in light blue.. I keep it mainly as a study note, but hopefully it might be of interest to fellow R users learning Python, and Python users learning R.
Mutable objects are changeable, they can be changed after they have been created. In contrast, immutable data objects can’t.
In Python, the distinctions are as follows
myTuple = (1,2,3,4,"five") # a tuple
myList = [1,2,3,4,"five"] # a list
While the above tuple and list look almost identical, they behave quite differently when we try to make changes to its items, because lists are mutable, while tuples are not. Therefore, item assignment is only supported for lists, but not for tuples in Python.
myList[4] = 5 # this changes the 5th element of the list
myList
## [1, 2, 3, 4, 5]
myTuple[4] = 5 # this returns an error because tuples are immutable
## Error in py_call_impl(callable, dots$args, dots$keywords): TypeError: 'tuple' object does not support item assignment
##
## Detailed traceback:
## File "<string>", line 1, in <module>
OK, but what if I need to make changes to a tuple, what do I do?
No problem, we can transform the tuple to a list using the list() function.
myTupleList = list(myTuple)
type(myTupleList)
## <class 'list'>
myTupleList[4] = 5
myTupleList
## [1, 2, 3, 4, 5]
I see, but why do use tuples at all, why don’t I use lists all the time then?
The immutable tuples have at least two advantages:
In R, item assignment is supported in both vectors and lists (examples below).
# vectors assume same data types, so in the following vector, every item is considered a character type.
myVector <- c(1,2,3,4,"five")
myVector[5] <- 5
myVector
## [1] "1" "2" "3" "4" "5"
myList <- list(1,2,3,4,"five")
myList[5] <- 5
myList
## [[1]]
## [1] 1
##
## [[2]]
## [1] 2
##
## [[3]]
## [1] 3
##
## [[4]]
## [1] 4
##
## [[5]]
## [1] 5
But just to complicate the issue a bit more, most R objects are actually immutable. When we are working with an immutable object, what happens under the hood is that a new object is created whenever we change its value or state.(more here)