Lists

Unit 3

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.

Further resources

What you’ve learned about lists covers the basics that we need for now. In the next units, we will use lists as a basic container data type to expand on our coding skills. If you come back to this page at a later time and desire more resources, I recommend the Chapter on Lists from the online course PY4E.

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.