Ad

How To Create A List In Python, Based Of Another Master List And User Input As Index?

- 1 answer

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?

Ad

Answer

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.

SelectedFruits.extend(Master[int(i):int(j)])

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']]
Ad
source: stackoverflow.com
Ad