Session 3 - Section: Wrap up of Variables and Using Modules

Variables Continue

While we have already discussed integers, float numbers and strings, we have not touched on compound data structures yet. The most versatile compound data structure is called a List.

Lists

A list is composed by multiple values (or variables) separated by a comma, enclosed in square brackets. Not all values need to be of the same type.

For example: x = [1, 2, "three", 4, 5]

You can access individual elements in a list by appending square brackets on the assigned variable, and the index of the value (remember, the index always starts at zero).

For example: x[0] represents the value 1. x[2] represents the value "three", etc.

Similarly, since we can access the vales individually, we can also assign them individually in the same manner.

For example: x[0] = "one" will transform the list to ["one", 2, "three", 4, 5]

Tuples

A tuple is similar to a list, where each value is separated by a comma, but with no brackets of any sort surrounding it.

For example: x = 1, 2, 3, 4, 5

Tuple items can be accessed like list (square brackets after the variable name), but values in the tuple cannot be changed (they are immutable). They are often used when one represents values in pairs, like coordinates (x, y).

Sets

Sets are unordered collections of items with no duplicates. Sets allow some set procedurs to run faster, like set comparisons.

Dictionaries

Dictionaries, also called associative arrays, are sequences indexed by a key rather than a numeric index.

For example: x = {'0': a, '1', b, '2': c} -> This emulates an actual list in python, but notice: x[1] gives an error. x['1'] gives us the values. Similarly:

x = {'fName': "Michalis", 'lName': "Avraam", 'major': "Geography"}

You can use x.has_key('fName') to see if the dictionary has such a key, or 'fname' in x as well.

Using Modules

Modules package functionality for us so we can reuse it. There are a lot of modules available in Python.

Importing a complete module

To import a model and all of its functionality, simply use the import statement.

For example: import math

Importing specific parts of modules

To import specific functionalities from a module, use the from module import part.

For example: from math import pi