Home > OS >  In a list, perform a task depending on the index values?
In a list, perform a task depending on the index values?

Time:03-03

Ok, so I have been trying to get specific indexes in my list "beans" to perform a task depending on the value of that index.

Here is the code:

def dude():
    beans = ['639', '939']
    bun = 0
    heyo_beans = beans[bun]
    while bun in range(len(beans)):   
        while bun in range(len(beans)):
            try:
                b = heyo_beans.index('639')
            except ValueError:
                print("Do Nothing")
                break
            else:
                print("Do something with variable b")
                break
        bun = bun   1
        print(bun)
    print(beans[1])
dude()

OUTPUT:

Do something with variable b
1
Do something with variable b
2
939

I should be getting:

Do something with variable b
1
Do Nothing
2
939

"Do Nothing" should appear the second go around as the index changed to index 2, which is 939. The final output of 939 is to verify that bean index 1 is indeed 939. Any ideas?

Another example would be:

list = ['111', '222', '333']
#goes through the list in a while loop, each time adding  1 index, for range in length
if list index = 111:
    "Perform task A"
elif list index = 222:
    "Perform task B"
elif list index = 333:
    "Perform task C"
else:
    "Do Nothing"
list index = index   1

Any suggestions on how to make this work?

This also does not work:

def dude():
    list_to_beans = ['639', '939']
    bun = 0
    heyo_beans = list_to_beans[bun]
    while bun in range(len(list_to_beans)):   
        for bun in list_to_beans:
            if heyo_beans == '639':
                print("Do something")
            else:
                print("Do nothing")
        bun = bun   1
    print(bun)

    
dude()

OUTPUT:

Do something
Do something

Should say:

Do something
Do nothing
2

CodePudding user response:

You're making this way more complicated than it needs to be. Just use an ordinary for loop to iterate over all the elements of the list. You're confusing indexes with the elements.

Since the list contains strings, you have to compare with strings, not numbers.

mylist = ['111', '222', '333']
for item in mylist:
    if item == '111':
        "Perform task A"
    elif item == '222':
        "Perform task B"
    elif item == '333':
        "Perform task C"
    else:
        "Do Nothing"

CodePudding user response:

Answer:

def dude():
    list_to_beans = ['639', '939']
    bun = 0
    heyo_beans = list_to_beans[bun]
       
    for heyo_beans in list_to_beans:
        if heyo_beans == '639':
            print("Do something")
        else:
            print("Do nothing")
    bun = bun   1
    print(bun)

    
dude()

OUTPUT:

Do something
Do Nothing
1
  • Related