Lists

Workshop 2 – Interactive classroom

A new data type: Lists

Lists
## List creation and access
categories = ["Low Consumption", "Moderate Consumption", "High Consumption"]
first_category = categories[0]             # Indexing
second_third_categories = categories[1:3]  # Slicing
last_category = categories[-1]             # Negative indexing

## List modification
categories.append("Unknown")               # Adding new element to end
categories.insert(0, "Net production")     # Insert new element at index
categories.remove("High Consumption")      # Remove element by value
categories.pop(1)                          # Remove element by index
categories[1] = "Modest Consumption"       # Modify element by index: Lists are mutable!

## List Operations
weird_list = categories + [110, ["a", "b"]] # Combining and nesting lists
len(weird_list)                             # Number of list elements (length)

Use these examples to explore lists interactively!

General python tip

Get a list of all methods available for a given object by

dir(weird_list)

If you want more information on the object and its methods, attributes, etc, consult the object documentation with

help(weird_list)

Hold on a second. What about weird_list?? This displays a few basic attributes of the object and the so-called documentation string (“docstring”), the plain-words description of the object. The documentation contains the docstring and much more.

Learning checklist

  • I know that lists are containers that can store (sequences of) strings, integers, floats, and other data types. Lists can also be nested (i.e., list of lists).
  • I know how to subset lists by indexing and slicing
  • I can find documentation about lists (and other objects) as well as get a quick overview of their methods.