## List creation and access
= ["Low Consumption", "Moderate Consumption", "High Consumption"]
categories = categories[0] # Indexing
first_category = categories[1:3] # Slicing
second_third_categories = categories[-1] # Negative indexing
last_category
## List modification
"Unknown") # Adding new element to end
categories.append(0, "Net production") # Insert new element at index
categories.insert("High Consumption") # Remove element by value
categories.remove(1) # Remove element by index
categories.pop(1] = "Modest Consumption" # Modify element by index: Lists are mutable!
categories[
## List Operations
= categories + [110, ["a", "b"]] # Combining and nesting lists
weird_list len(weird_list) # Number of list elements (length)
Lists
Workshop 2 – Interactive classroom
A new data type: Lists
Lists
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.