CSU East Bay logo

Chemistry 311

Lists and Dictionarys in Python

Python provides several built-in data structures for storing and organizing collections of data. The most commonly used are lists, tuples, sets, and dictionaries. Each is designed for a different purpose, and choosing the right one makes programs clearer and more efficient.


Lists

A list is an ordered, mutable collection of values. Lists can contain items of different data types and can be changed after they are created.


    numbers = [1, 2, 3, 4]
    names = ["HCl", "CO2", "NH3"]
    mixed = [1, "text", 3.14]
      

Lists are commonly used when you need to store a sequence of items and modify it by adding, removing, or updating elements.

Lists in Python are ordered collections, which means each element has a specific position. Indexing allows you to access individual elements in a list by referring to their position.


Basic list indexing

Python uses zero-based indexing, meaning the first element in a list has index 0.


      molecules = ["HCl", "CO2", "NH3"]
        

In this list:

  • molecules[0] refers to "HCl"
  • molecules[1] refers to "CO2"
  • molecules[2] refers to "NH3"

Attempting to access an index that does not exist will result in an error:


      molecules[3]  # IndexError
        

Negative indexing

Python also allows negative indices, which count from the end of the list.

  • molecules[-1] refers to the last element ("NH3")
  • molecules[-2] refers to the second-to-last element ("CO2")

Negative indexing is useful when you want to access elements relative to the end of a list without knowing its length.


Modifying list elements

Because lists are mutable, you can change elements by assigning a new value to a specific index.


      molecules[1] = "O2"
        

After this assignment, the list becomes ["HCl", "O2", "NH3"].

In addition to indexing individual elements, Python allows you to extract subsets of a list using a feature called slicing. Slicing creates a new list containing selected elements from the original list.


Basic slicing syntax

The general form of a slice is:


        my_list[start : stop]
          

This returns a new list beginning at index start and ending before index stop.


        values = [10, 20, 30, 40, 50]
        values[1:4]   # [20, 30, 40]
          

Omitting start or stop

If start is omitted, slicing begins at the start of the list. If stop is omitted, slicing continues to the end of the list.


        values[:3]    # [10, 20, 30]
        values[2:]    # [30, 40, 50]
          

Negative indices in slicing

Slices can use negative indices to count from the end of the list.


        values[-3:-1]   # [30, 40]
          

Step values

A third parameter can be included to specify a step size:


        my_list[start : stop : step]
          

        values[::2]    # [10, 30, 50]
        values[::-1]   # [50, 40, 30, 20, 10]
          

Big idea: slicing provides a flexible and readable way to extract, copy, or reorder parts of a list without modifying the original list.


Big idea: list indexing provides direct access to individual elements, and understanding zero-based and negative indexing is essential for working effectively with lists in Python.


Tuples

A tuple is an ordered collection of values that is immutable, meaning it cannot be changed after creation.


    coordinates = (3.0, 4.0)
    constants = (6.626e-34, 2.998e8)
      

Tuples are useful for representing fixed collections of values that should not be altered, such as coordinates or physical constants.


Sets

A set is an unordered collection of unique values. Duplicate entries are automatically removed.


    elements = {"H", "C", "O", "H"}
      

In this example, the set will contain only {"H", "C", "O"}. Sets are useful for membership testing, removing duplicates, and performing mathematical set operations such as unions and intersections.


Dictionaries

A dictionary stores data as key–value pairs. Values are accessed by their keys rather than by position.


    molecule = {
        "name": "HCl",
        "bond_length": 1.27,
        "dipole_moment": True
    }
      

Dictionaries are ideal for representing structured data where each value has a descriptive label.


Example: a list of dictionaries

Complex data are often represented by combining these structures. A common pattern is a list of dictionaries, where each dictionary represents one record.


    molecules = [
        {"name": "HCl", "bond_length": 1.27},
        {"name": "CO2", "bond_length": 1.16},
        {"name": "NH3", "bond_length": 1.01}
    ]
      

This structure allows you to store multiple objects while keeping related properties grouped together.


Choosing the right data structure

Big idea: Python’s built-in data structures provide flexible ways to organize information, and selecting the appropriate structure leads to clearer, safer, and more expressive code.

Your turn

Problem 1
Which Python data structure is ordered and mutable?
Tuple
List
Set
Dictionary
Problem 2
Which data structure automatically removes duplicate values?
Set
List
Tuple
Dictionary
Problem 3
Which data structure stores values as key–value pairs?
List
Tuple
Set
Dictionary
Problem 4
Which situation is best suited for using a tuple instead of a list?
Storing a collection that will change frequently
Removing duplicate values from a dataset
Representing a fixed set of values that should not change
Associating labels with values
Problem 5
Why might a programmer choose a list of dictionaries to store data?
Because dictionaries must always be stored in lists
To store multiple records while keeping related data grouped together
Because sets cannot contain dictionaries
To guarantee the data will never change
Problem 6
Given the list

values = [10, 20, 30, 40]
          
what does values[0] return?
10
20
30
An error
Problem 7
Using the same list

values = [10, 20, 30, 40]
          
what does values[-1] return?
10
20
40
An error
Problem 8
What happens when you execute the following code?

items = ["a", "b", "c"]
items[1] = "z"
          
The code produces an error
The list becomes ["a", "z", "c"]
The list becomes ["z", "b", "c"]
The list cannot be modified
Problem 9
Given the list

values = [10, 20, 30, 40, 50]
          
what does the expression values[1:4] return?
[10, 20, 30]
[20, 30]
[20, 30, 40]
[30, 40, 50]

Key points (one glance)

Big picture: understanding how Python’s core data structures work allows you to model real-world information effectively and write programs that are easier to read, maintain, and extend.