Expanders not collapsing

I have simplified my code into the following:

x = st.slider("Slider",min_value=1, max_value=10)

for i in range(x):
    with st.expander("Test"):
        st.write(i)

The problem for me is that say the slider is at 2, resulting in two expander and I click the first expander open. If I then make the slider 4, I will have 4 expanders but the first one is still open. I want all the expanders to collapse once the slider/input changes. I have tried buttons with session state but no luck.

Streamlit will avoid to remount containers that do not change between reruns. A hacky workaround is to modify the expander’s label at each interaction, like adding some random whitespace character at the end:

import streamlit as st
from string import whitespace
from random import choice

x = st.slider("Slider", min_value=1, max_value=10, value=1)

for i in range(x):
    with st.expander(f"Test {choice(whitespace)}"):
        st.write(i)