Lecture 5 - Container types and indexing

Essential Skills For Computational Biology

2020-06-16

Kevin Bonham, PhD

Scalars and Containers

  • A "scalar" is a singular value

  • Most of the types you've seen so far are scalars

    • Eg. Float64, Int64, Bool, Char
  • There are also many container types, which store multiple values

  • Containers can usually be accessed by an "index"

A Tuple is a simple, ordered container

my_tuple = (1, 1.2, "a string")
(1, 1.2, "a string")

Each position has an integer index, 1 for the first position, 2 for the second, and so on

my_tuple[1]
1
my_tuple[3]
"a string"

Attempting to access an index that doesn't exist is an error

length(my_tuple)
3
my_tuple[4]

A Vector is a mutable, ordered container

Vectors can by easily created with [ and ]

my_vector = [1,3,5,7]
4-element Array{Int64,1}:
 1
 3
 5
 7

Each position has an integer index, 1 for the first position, 2 for the second, and so on

my_vector[1]
1
my_vector[2]
3

Add to the end of a Vector with push!()

push!(my_vector, 50);
my_vector

other_vector = [] ## an empty vector
for i in 1:2:10
    push!(other_vector, i)
end
other_vector
5-element Array{Any,1}:
 1
 3
 5
 7
 9

Change the value of a vector by assignment (=)

my_vector[1] = 42;
my_vector
5-element Array{Int64,1}:
 42
  3
  5
  7
 50

Index a "slice" with a range

my_vector
5-element Array{Int64,1}:
 42
  3
  5
  7
 50
my_vector[2:4]
3-element Array{Int64,1}:
 3
 5
 7

Attempting to access an index that doesn't exist is an error

length(my_vector)
5
my_vector[6]

Dictionaries are containers with "key" => "value" pairs

  • Keys can be any scalar type
  • Keys are used as indexes
  • Values can be scalars or other containers
  • Keys are unordered

Create a Dictionary with Dict()

my_dict = Dict("key1"=> 42, "key2"=> 1.8, 5=> "a value")
Dict{Any,Any} with 3 entries:
  "key2" => 1.8
  5      => "a value"
  "key1" => 42

The keys are used to index

my_dict["key1"]
42
my_dict[5]
"a value"

Values can be reassigned

my_dict["key1"] = 3.14
3.14

Attempting to access with a key that doesn't exist is an error

my_dict["I don't exist"]

But you can assign a new key-value pair

my_dict["I don't exist... yet"] = "Now I do!"
"Now I do!"
my_dict["I don't exist... yet"]
"Now I do!"

You can use haskey() (a Boolean function) to see if a dictionary already has a key

haskey(my_dict, "key1")
true
haskey(my_dict, "key1000")
false

Questions?


This page was generated using Literate.jl.