Skip to main content
Every time a user interacts with a widget (clicks a button, types in a text box, or adjusts a slider), Streamlit reruns the entire Python script from top to bottom. By default, any local variables you declare are reset to their original values during a rerun. To preserve values and pass data across runs, you must use Session State (st.session_state).

1. How Session State Works

st.session_state behaves like a Python dictionary. You can store key-value pairs that persist throughout a user’s session.

Initializing values

Always check if a key exists in session state before using or modifying it, otherwise you will re-initialize it on every rerun:

Reading and Writing values

You can access and update keys using either attribute or dictionary syntax:

2. Practical Example: Student Grade Logger

Here is a practical example of using session state to store a list of logged students. Each time you click the “Add Student” button, the script reruns, but the list of students is preserved and updated. Create a file named exercise_session_state.py:
Run the script: