Sequence data types in Python

Dr. Huidae Cho
Institute for Environmental and Spatial Analysis...University of North Georgia

1   Tuples

Tuples are array-like immutable objects.

Immutable objects cannot be modified once defined.

Elements are accessed using a 0-based index.

x = (1, 2.3, '4', [10, 20]) # create a tuple with different data types
len(x)                      # tuple size
x[0]                        # first element
x[0] = 10                   # try to modify it
x[3][0]                     # 2-dimensional indexing
x[3][0] = 1                 # works?

2   Lists

Lists are array-like mutable objects.

Mutable objects can be modified.

Elements are accessed using a 0-based index.

x = [1, 2.3, '4', (10, 20)] # create a list with different data types
len(x)                      # list size
x[0]                        # first element
x[0] = 10                   # try to modify it
x[3][0]                     # 2-dimensional indexing
x[3][0] = 1                 # works?

3   Slicing array-like objects

Slicing array-like objects is not any different from slicing strings.

Use the same slicing method to access individual elements in an array-like object.

4   Exercise: Reading a GeoTIFF file as a matrix using NumPy

  1. Download elevation.tif.
  2. Open ArcGIS Pro with no templates.
  3. Open the Python window: View ⇒ Python
  4. Learn about the GDAL and NumPy modules.
# we'll use the gdal module
import gdal

# read in elevation.tif as a GDAL dataset object; of course, use your path to elevation.tif; it'll lock elevation.tif
ds = gdal.Open('p:/tmp/elevation.tif')
type(ds)

# type ds + <dot> and see the list of attributes
# ds.

# let's see how many bands we have in elevation.tif
ds.RasterCount

# get the first and only band; note here that band numbering is 1-based
band = ds.GetRasterBand(1)
type(band)

# read the band as a matrix
arr = band.ReadAsArray()
type(arr)

# now, release elevation.tif; no more access to ds and band
del ds, band

# what is its dimension?
arr.shape

5   Exercise: Reading a GeoTIFF file as a matrix using ArcPy

  1. Download elevation.tif.
  2. Open ArcGIS Pro with no templates.
  3. Open the Python window: View ⇒ Python
  4. Learn about the NumPy module.
# read in elevation.tif as a Raster object; of course, use your path to elevation.tif; it'll lock elevation.tif
ras = arcpy.Raster('p:/tmp/elevation.tif')
type(ras)

# type ras + <dot> and see the list of attributes
# ras.

# let's see how many bands we have in elevation.tif
ras.bandCount

# read the band as a matrix
arr = arcpy.RasterToNumPyArray(ras)
type(arr)

# now, release elevation.tif; no more access to ras
del ras

# what is its dimension?
arr.shape