How is it possible to index an item in a list and pull up the same index position from another list

Viewed 12

I am trying to pull up the same index position from another list after I have successfully indexed an item in a different list.

Basically, I have a list of fruits and their prices during the weekdays and during the weekend. The very exact fruit is being taken as an input and if the fruit is in the list then I am indexing it. The day of the week is also an input and if the day is in the workdays I want to take the same index position from the list of the weekdays prices in order to correspond with the very exact fruit's index position. Same as if the day is Saturday or Sunday - taking the index position from the weekend price list.

Here is the code:

fruits=["banana","apple","orange","grapefruit","kiwi","pineapple","grapes"]
weekdays=["Monday","Tuesday","Wednesday","Thursday","Friday"]
weekdays_price=[2.50,1.20,0.85,1.45,2.70,5.50,3.85]
weekend=["Saturday","Sunday"]
weekend_price=[2.70,1.25,0.90,1.60,3,5.60,4.20]

fruit=input()
day=input()
quantity=float(input())

if fruit in fruits:
    fruit_index=fruits.index(fruit)
    if day in weekdays:
        pass
        #taking the same index from weekdays_price and multiplying it's item value by the quantity
    elif day in weekend:
        pass
        #taking the same index from weekend_price and multiplying it's item value by the quantity
    else:
        print("error")
else:
    print("error")

So for example if the user enters "apple","Monday" and 2 Python should print out 2.40 ("apple" index position is 1, "Monday" is in weekdays so we are taking index position 1 from weekdays_price (1.20) and multiplying it by the quantity (2)).

1 Answers

You can "index" a list using list[index]:

my_list = [10, 20, 30, 40, 50, 60, 70]
index = 5

my_list[index]
# returns 60, the element with index 5 in my_index (the 6th element)

So in your case, the if-block becomes:

if day in weekdays:
    price = weekdays_price[fruit_index]
    print(price * quantity)

and similar for weekend, just replacing weekdays_price with weekend_price.

PS:

  1. Should quantity really be a float? I can imagine that you'd typically only be able to order an integer amount of apples, say 3 apples, not 3.5. Weird supermarket that sells half apples ;)
  2. It would be nice if your error messages were more descriptive, for instance print("Error: fruit not found") and print("Error: day not found"). This way you would know what went wrong if something were to go wrong.
Related