How do I unpack a list with a varying amount of items into individual variables?

83 Views Asked by At
import streamlit as st

sidebar_counter = 9
# this number can vary depending on what is selected by the user

column_list = [col1, col2, col3, col4, col5]
# column_list can vary and be a list that is [col1, col5] and just two items depending on what is selected by the user

#my goal is to assign each col# to each column as follows:
col1, col2, col3, col4 = st.columns(sidebar_counter)

# where sidebar_counter will already include the number of columns selected.

is there any way to dynamically unpack the col1, col2, col3 depending on what is selected?

I have tried the following:

import streamlit as st

column_list = st.columns(sidebar_counter)

However, this does not work as when I call any columns (col1 for example), it is not defined.

2

There are 2 best solutions below

4
gamez_code On

You can set the variable in the global dictionary, and then you can call the variable in your script. For example:

for s in range(sidebar_counter):
    globals()[f"col{s+1}"] = column_list[s]

Alternatively, you can set the variable in the local dictionary and then call the variable into a function. For example:

for s in range(sidebar_counter):
    locals()[f"col{s+1}"] = column_list[s]

However, in my opinion, the best approach is to save the variable in a regular dictionary, and then you can work with that dictionary.

0
ferdy On

Have you tried this?

import streamlit as st

sidebar_counter = 9
column_list = st.columns(sidebar_counter)

for i in range(sidebar_counter):
    with column_list[i]:
        st.write(f'column {i+1}')
        # other stuffs ...

Output

enter image description here