8 List and list indexing
- List in R and Python can include different data types
- List operation differs between two languages
8.1 R
Lst <- list(x = 5, y = 3.5, w = 'David', z = TRUE, s = 'Another string', v = c(1,3,5))
Index | Explanation | Example. |
---|---|---|
$ |
Get the elements by names | Lst$x |
[i] |
Get the element at the specific location. The outcome is a LIST. | Lst[1]; Lst[3] |
[[i]] |
Get the element at the specific location. The outcome is the corresponding CLASS. | Lst[[1]]; Lst[[3]] |
Positive integer | Get the element at the specific location | Lst[2]; Lst[[2]] |
Negative integer | Remove the element at the specific location and return the rest. | Lst[-2] |
Zero | Get no element. Only valid with [i]. | Lst[0] |
Blank | Get all elements. Only valid with [i] . |
Lst[] |
Logical values | Get the element for the location is TRUE. Only valid with [i]. | Lst[c(T,T,F,F)] |
Names | Get the named element | Lst$x |
8.2 Python
Lst = [5, 3.5, 'David', True, 'Another string', v = c[1,3,5] ]
Python slicing and dicing operations are carried through the following logic: Lst[start:stop:step]
Index | Explanation | Example. |
---|---|---|
start | The starting position (0 indexing applies) | Lst[2]; Lst[1:] |
end | The starting position (0 indexing applies) | Lst[:4]; Lst[1:5] |
step | The step values | Lst[1:4:2]; Lst[::-1] |
negative integer | Different behaviours depending on start, stop or step |
Important list methods:
append
, extend
, insert
, remove
, pop
, index
, count
, sort
, reverse
8.3 Python-specific objects
Tuple
Tuple stores multiple fixed values in a sequence.
It uses \(()\) to include the values
= ("apple", "banana", "cherry", "apple", "cherry", "cherry")
tup
print(tup)
(‘apple’, ‘banana’, ‘cherry’, ‘apple’, ‘cherry’, ‘cherry’)
Set
Set stores multiple unique values in an unordered collection.
It uses \({}\) to include the unique values
= {"apple", "banana", "cherry", "apple", "cherry", "cherry"}
fset
print(fset)
{‘cherry’, ‘banana’, ‘apple’}
Dictionary
Dictionary stores multiple unordered key:value pairs.
= {"apple": 2, "banana": 1, "cherry": 3}
fdict
print(fdict)
{‘apple’: 2, ‘banana’: 1, ‘cherry’: 3}