Home > other >  I have functioning code, but I would like it to return the list object name instead of the position
I have functioning code, but I would like it to return the list object name instead of the position

Time:07-14

Apples = 1
Oranges = 0
Bananas = 1
Grapes = 0

list1 = [Apples, Oranges, Bananas, Grapes]
y = len(list1)

for x in range(0,y):
    if list1[x] == 1:
        print (x)

This code will print out the locations of the variables with values of 1: 0,2

Would like this to print out the names of the variables instead of the locations (so Apples and Bananas).

Edited code with dictionary method (printing out all fruit names though):

Apples = 1
Oranges = 0
Bananas = 1
Grapes = 0


FruitValues = {"Apples": Apples,"Oranges": Oranges,"Bananas": 
Bananas,"Grapes": Grapes}

myFruits = ["Apples", "Oranges", "Bananas", "Grapes"]


for x in myFruits:
    if x in FruitValues:
        print(f"{x}")

Here is an idea but not working:

Apples = 1
Oranges = 0
Bananas = 1
Grapes = 0


FruitValues = {"Apples": Apples,"Oranges": Oranges,"Bananas": 
Bananas,"Grapes": Grapes}

myFruits = ["Apples", "Oranges", "Bananas", "Grapes"]


for x, y in FruitValues.items():
    if y in FruitValues == 1:
        print(y)

CodePudding user response:

I'd recommend using a dictionary to assign values to elements

FruitValues = {
  "Apples": 1,
  "Oranges": 0,
  "Bananas": 1,
  "Grapes": 0
}

then you can create a list of fruits

myFruits = ["Apples", "Oranges", "Bananas", "Grapes"]

the you can iterate over the list nd check if the fruit exist in your dictionary

for fruit in myFruits:
    # Print the fruit if it has a value of 1
    if fruit in FruitValues and FruitValues[fruit] == 1:
        print(f"{fruit} has a value of {FruitValues[fruit]}")

CodePudding user response:

You almost had it at the end.

for x, y in FruitValues.items():
    if y == 1:
        print(x)

CodePudding user response:

print(list1[x])

because the x is the location and you need to access the value.

Happy Coding

  • Related