1

I have a function in python that checks if the value of listy_poo[0] is a certain value. If it is, I need to skip index 1 and get the value of index 2.

My code:

def find():
    i = 0
    for e in listy_poo:
        if listy_poo[i] == 'value':
            print(listy_poo[i+2])
            i += 1

Clearly wrong, but is there something in python that accomplishes what I'm attempting?

UPDATE: I thought the problem was the syntax of listy_poo[i+2] but looking over the history has shown that I actually didn't save my change from when I attempted listy_poo[i]+2, which is wrong. Thanks for your help anyway, folks.

2
  • you want to do your same logic for 1st element as well (The logic that you perform for element with index 2 onwards)? Commented Oct 22, 2015 at 18:42
  • No, I need to skip the first element. The list is formatted in a way that guarantees that if 'value' is found, then exactly two elements over is another value which I need to extract. Commented Oct 22, 2015 at 18:44

1 Answer 1

1

Your code is close to working. If you change it to

def find(listy_poo, value_str):
    for i, e in enumerate(listy_poo):
        if e == value_str and i+2 < len(listy_poo):
            print(listy_poo[i+2])

The enumerate() function returns a tuple of the index of the given item in the list, and the item itself. I also added a check (i+2 < len(listy_poo)) to make sure you don't get an IndexError.

Looking at your description, I'm not positive this is doing what you want.

If you ran find(['a','b','c','d'],'b') then the function would print out d. That is, whenever it finds a match for the value, it moves over two spots in the list, and prints that value. Is that what you are going for?

Sign up to request clarification or add additional context in comments.

1 Comment

Even though the bug I caught in my code fixed the basic functionality, this is a better solution for what I need. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.