Containers - lists and dictionaries

Python for R Users

Daniel Chen

Instructor

Lists

  • Similar to the R vector and list
  • Holds heterogeneous information (e.g., [3, 2.718, True, 'hello'])
Python for R Users

Creating lists

R
l <- list(1, "2", TRUE)
l
[[1]]
[1] 1

[[2]]
[1] "2"

[[3]]
[1] TRUE
Python
l = [1, '2', True]
l
[1, '2', True]
Python for R Users

Python is 0-indexed

Python is a 0-indexed language

Python for R Users

Subsetting lists

R

Get the 1st element from R list

l[[1]]  # use 1
1
Python

Get the 1st element from Python list

l[0] # use 0
1
Python for R Users

Negative indices

Negative indices start counting from the end

Python for R Users

Negative indices

R
l <- list(1, "2", TRUE)
l[-1]
[[1]]
[1] "2"

[[2]]
[1] TRUE
Python
l = [1, "2", True]
l[-1]
True
Python for R Users

Left inclusive right exclusive

Left inclusive, right exclusive

Python for R Users

Think fence posts

index 0           1           2           3           4           5
      |           |           |           |           |           |
      | element 0 | element 1 | element 2 | element 3 | element 4 |
      |           |           |           |           |           |
Python for R Users

Slicing part 1

Python
l = [0, 1, 2, 3, 4]

l[0:3]
[0, 1, 2]
l[0:5:2]
[0, 2, 4]
Python for R Users

Slicing part 2

Implicit
l[:3]
[0, 1, 2]
l[1:]
[1, 2, 3, 4]
l[::2]
[0, 2, 4]
Explicit
l[0:3]
[0, 1, 2]
l[1:5]
[1, 2, 3, 4]
l[0:5:2]
[0, 2, 4]
Python for R Users

Dictionaries

  • Lists are unlabeled
  • Dictionaries provide key:value pairs
Python for R Users

Python: Creating and working with dictionaries

d = {'int_value':3, 'bool_value':False, 'str_value':'hello'}

d
{'int_value': 3, 'bool_value': False, 'str_value': 'hello'}
d['str_value']
'hello'
Python for R Users

Finding the length

l = [0, 1, 2, 3, 4]
d = {'int_value':3, 'bool_value':False, 'str_value':'hello'}

len(l)
5
len(d)
3
Python for R Users

Let's practice!

Python for R Users

Preparing Video For Download...