I’m very curious how to define a function that contains st.expander and a beginner code like take input, append to list (twice), show the list (with at least two items in it).
Thank you very much.
import streamlit as st
my_list = []
def manager():
with st.expander("Example"):
st.write(my_list) #was
user_input = st.text_input("Enter a key")
add_button = st.button("Add", key='add_button')
if add_button:
if len(user_input) > 0:
my_list.append(user_input)
st.write(my_list) #is
else:
st.warning("Enter text")
if __name__ == '__main__':
manager()
import streamlit as st
# initiate empty list to add items to
lst = []
def append_to_lst(my_input=['test_input'], my_lst=lst):
"""
Append items from the input list to the provided list and display the updated list in a Streamlit expander.
Parameters:
my_input (list): The list of items to be appended to the target list. Default is ['test_input'].
my_lst (list): The target list to which the items will be appended. Default is lst.
Returns:
None
"""
for my_item in my_input:
my_lst.append(my_item)
with st.expander('LIST', expanded=True):
st.write(my_lst)
# apply function to add items to list and show in streamlit list
append_to_lst(['test1', 'test2', 'test3'])
# apply function to add more items to list and show in streamlit list again
append_to_lst(['test4', 'test5', 'test6'])
Hi, thanks for your answer. However, I see you didn’t implement user input that takes an input from a user and appends to a list. Sending you the code that needs an explaination.
P.S. Yes, this could be bypassed by storing the data in a file, however, that’s not likely. Moreover, I tried to make it in a while loop that non stop appends data to a list, streamlit couldn’t handle that, just hang.
import streamlit as st
my_list = []
def manager():
with st.expander("Example"):
st.write(my_list)
user_input = st.text_input("Enter a key")
add_button = st.button("Add", key='add_button')
if add_button:
if len(user_input) > 0:
my_list.append(user_input)
st.write(my_list)
else:
st.warning("Enter text")
if __name__ == '__main__':
manager()
@armM00 Thank you for your example code, that clarifies your goal. Below my example with using session state to store the list in:
import streamlit as st
if 'my_lst' not in st.session_state:
st.session_state['my_lst'] = []
def manager():
with st.expander("Example"):
user_input = st.text_input("Enter a key")
add_button = st.button("Add", key='add_button')
if add_button:
if len(user_input) > 0:
st.session_state['my_lst'] += [user_input]
st.write( st.session_state['my_lst'] )
else:
st.warning("Enter text")
if __name__ == '__main__':
manager()