Session_state for storing matrices

Summary

Hi, I try to store the values of a matrix with session_state.

This code doesn’t seem to work:

Code snippet:

a = [[0]*10 for i in range(10)]
if 'a[i][j]' not in st.session_state:
    st.session_state[a[i][j]] = a[i][j]

Is it the right way to use session_state for matrices ?

Thanks.

You’ll want to store the whole matrix in st.session_state and access the whole thing in turn.

if 'my_matrix' not in st.session_state:
    st.session_state.my_matrix = [[0]*10 for i in range(10)]

# Access and work with your matrix, for example
st.session_state.my_matrix[2][3] = 4

Thanks for the answer.

I get this kind of error message though: "AttributeError: ‘list’ object has no attribute ‘my_matrix’ "

That was my bad in copying down what I meant. I’ve corrected it. The line inside the conditional was meant to initialize the key/value pair so that it could then be called upon.

if 'my_matrix' not in st.session_state:
    st.session_state.my_matrix = [[0]*10 for i in range(10)]

# Access and work with your matrix, for example
st.session_state.my_matrix[2][3] = 4

Thanks again.
I had corrected it myself, but still get the same error message…

@blob123 It seems like perhaps you’re overwriting st.session_state itself with a list, something like this perhaps:

st.session_state = [...]

Are you doing that somewhere in your script? If not, can you share a complete minimal script which reproduces that error message?

For example, this works fine:

import streamlit as st

if "my_matrix" not in st.session_state:
    st.session_state.my_matrix = [[0] * 10 for i in range(10)]

# Access and work with your matrix, for example
st.session_state.my_matrix[2][3] = 4

st.write(st.session_state)

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.