How to dynamically create a number of columns and insert an element into each

My app would involve allowing the user to choose the number of inputs he wishes to enter
For example, at the top, there would be a select box asking the user for the number of inputs, say 1 to 5, I’ll call this n_input.

And then, I would like there to be that number of select boxes to show up. So for example, the user selected “3” in the previous n_input select box, then 3 select boxes would show up which allow the user to input 3 items.

This is not that difficult to accomplish:
for i in range(n_input):
input[i]=st.selectbox("Input # "+str(i),[1,2,3],key=i)

However, I don’t know how to pack them into columns instead of just lining up vertically. The number of variables to unpack ranges from 1 to 7 so this requires some dynamic assignment.


Surely, I could make a big if loop,

if n_input==7:
if n_input==6:
if n_input==5:

Is there a better way to do this?

Hi @terbiume65, welcome to the Streamlit community!

You can accomplish what you are talking about using the following:

import streamlit as st

ncol = st.sidebar.number_input("Number of dynamic columns", 0, 20, 1)
cols = st.beta_columns(ncol)

for i, x in enumerate(cols):
    x.selectbox(f"Input # {i}",[1,2,3], key=i)


1 Like