Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get next element from list after search string match in python

Tags:

python

Hi Friends I have a list where I'm searching for string and along with searched string I want to get next element of list item. Below is sample code

>>> contents = ['apple','fruit','vegi','leafy']
>>> info = [data for data in contents if 'fruit' in data]
>>> print(info)
['fruit']

I want to have output as fruit vegi

like image 280
Bhaskar vedula Avatar asked Jan 01 '26 03:01

Bhaskar vedula


2 Answers

What about:

def find_adjacents(value, items):
    i = items.index(value)
    return items[i:i+2]

You'll get a ValueError exception for free if the value is not in items :)

like image 104
el.atomo Avatar answered Jan 03 '26 17:01

el.atomo


I might think of itertools...

>>> import itertools
>>> contents = ['apple','fruit','vegi','leafy']
>>> icontents = iter(contents)
>>> iterable = itertools.dropwhile(lambda x: 'fruit' not in x, icontents)
>>> next(iterable)
'fruit'
>>> next(iterable)
'vegi'

Note that if you really know that you have an exact match (e.g. 'fruit' == data instead of 'fruit' in data), this becomes easier:

>>> ix = contents.index('fruit')
>>> contents[ix: ix+2]
['fruit', 'vegi']

In both of these cases, you'll need to specify what should happen if no matching element is found.

like image 23
mgilson Avatar answered Jan 03 '26 16:01

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!