How To Create A List In Python, Based Of Another Master List And User Input As Index?
I'm relatively new to Python.
I have a list like
Master = ['Apple','Banana','Clementines','Dates','Fig','Guava']
I would like to get user input like
Choose your fruits: > 1,3:5
Based on user input, I want to create a sub-list like
SelectedFruits = ['Apple','Clementines','Dates','Fig']
If I perform command as follows, I get an error that the index is a string.
UserInput = input() SelectedFruits = Master[UserInput]
Can you kindly help?
You can do it like this;
Master = ['Apple','Banana','Clementines','Dates','Fig','Guava'] inp = input().split(",") # input is "1,3:5" SelectedFruits =  for elem in inp: if ":" in elem: i, j = elem.split(":") SelectedFruits.extend(Master[int(i):int(j)]) else: i = int(elem) SelectedFruits.append(Master[i]) # ['Banana', 'Dates', 'Fig']
Assuming the input is entered one time with commas, you can split them first, then put in a for loop.
What I did in the solution is to check for ":" s in each input to see if it is an index. Then I stack them in a tuple as such (i,j) to later use as indexes because tuple cannot be used directly as index.
And take care that every the time we use these values we have to convert them to integers because default inputs are always strings.
I used extend(), instead of append() in this part because the indexes we use, causes it to return another list inside list so it would look like this if we hadn't done that:
['Banana', ['Dates', 'Fig']]
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module