Update list option list with session

Hi all,

I try to use a session state to remove an item from a list (i want in the second step to use this new list, to select another item from it).

My minimal code is here (I have commented out the 2nd select box, since it throws the error before)

import streamlit as st 

if 'teams' not in st.session_state:   
    st.session_state['teams'] = ['GER', 'FRA', 'NED', 'USA', 'UAE', 'ISR', 'THA', 'COL']

teamA_name = st.sidebar.selectbox("Team A", options=st.session_state['teams'])

teamA_name_sub = st.sidebar.button('Submit Team A',key="Team A key")
if teamA_name_sub:
    st.session_state['teams'].remove(teamA_name)
    st.header(teamA_name)
    #teamB_name = st.sidebar.selectbox('Team B', options=st.session_state['teams'])
    #teamB_name_sub = st.sidebar.button('Submit Team B', key="Team B key" )

st.write(st.session_state['teams'])

The error occurs after I press the submit button and says:

  File "/Users/behnk001/Library/Python/3.8/lib/python/site-packages/streamlit/elements/selectbox.py", line 120, in serialize_select_box
    return index_(opt, v)
  File "/Users/behnk001/Library/Python/3.8/lib/python/site-packages/streamlit/util.py", line 129, in index_
    raise ValueError("{} is not in iterable".format(str(x)))
ValueError: NED is not in iterable

So it somehow does not like the remove function.

Any ideas about what I do wrong?

Thanks a lot :slight_smile:

Hi @ClaudiaBehnke86 ,

I think the reason why it is complaining is because you are not only trying to change the options list for the teamB_name selectbox, but also the options list for the teamA_name selectbox. Once you click the submit button, you will remove the teamA_name variable from the session_state['teams'], and therefore you remove it from the teamA_name selectbox options. Therefore you have created a workflow that --after clicking the submit button-- removes the chosen option from the list, making it impossible to select the item you want to select.

I recommend to not change session_state['teams'] after you created it. Instead, I would do this:

teamA_name = st.sidebar.selectbox("Team A", options=st.session_state['teams'])
teamB_name = st.sidebar.selectbox('Team B', options=[x for x in st.session_state['teams'] if x != teamA_name)

This method filters the list to remove the item that was already picked, while not affecting the session_state['teams'] list.

Hopefully this solves your issue!

Cheers,
Dirk

This worked perfectly!
And is much easier than all my complications with the submit button :wink:

@DirkRemmers i have a situation like 2 selectboxes, 1 with regions and another 1 one with countries. how to write the session state for both selectboxes such that when region APAC is selected, countries related to APAC region only to be visible as option and vice versa.

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