John Taylor
John Taylor

Reputation: 737

Find list item then get next list item

Trying to find an item in a list then get the very next list item

I have tried iterators, the enumerator function. No dice.

lst = ['SOME TEXT FOR THE FIRST ITEM','THE COURT FINDS THAT A COMMUNITY CONTROL SANCTION WILL ADEQUATELY PROTECT THE PUBLIC AND WILL NOT DEMEAN THE SERIOUSNESS OF THE OFFENSE.', 'IT IS THEREFORE ORDERED THAT THE DEFENDANT IS SENTENCED TO 2 YEAR(S) OF COMMUNITY CONTROL, UNDER SUPERVISION OF THE ADULT PROBATION DEPARTMENT WITH THE FOLLOWING CONDITIONS: DEFENDANT TO ABIDE BY THE RULES AND REGULATIONS OF THE PROBATION DEPARTMENT.', 'LAST ITEM IN THE LIST']




for x in lst:
    lst_item = iter(lst)
    if "WILL ADEQUATELY PROTECT" in x:
        print(next(lst_item))

Expecting to get the very next list item following the item containing the string searched for.

Upvotes: 0

Views: 62

Answers (2)

rassar
rassar

Reputation: 5660

The enumerate function should work:

for index, item in enumerate(lst):
    if "WILL ADEQUATELY PROTECT" in item:
        print(lst[index + 1])

The issue with your code is that you are calling iter on the whole list, not the list after the item you want. If you want to use the iter method, you can do:

it = iter(lst)
for item in it:
    if "WILL ADEQUATELY PROTECT" in item:
        print(next(it))

Upvotes: 3

minterm
minterm

Reputation: 258

The most straightforward way would be:

for i in range(len(lst)):
    if "WILL ADEQUATELY PROTECT" in lst[i] and i < len(lst) - 1:
        print(lst[i+1])

Upvotes: -1

Related Questions