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: Read a GeoTIFF file as a NumPy array using GDAL

  1. Download elevation.tif.
  2. Start a new JupyterLab notebook.
  3. Learn about the GDAL and NumPy modules.
  4. Try this code line by line.
  5. Check this article for more explanations.
# we'll use the gdal module
from osgeo 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)

# see the list of attributes
dir(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 NumPy array
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: Read a GeoTIFF file as a NumPy array 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 NumPy array
arr = arcpy.RasterToNumPyArray(ras)
type(arr)

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

# what is its dimension?
arr.shape

6   Exercise: List and indexing

Let’s see how we can access individual elements in a list.

A = [12, 34, 45, 67]
print(A[0])
print(A[3])