Federico Gentile Federico Gentile - 1 year ago 79
Python Question

How to select a chunk of list between two values in python

I have a list of values like this:

vect_i = ['a','X','c','g','X','t','o','X','q','w','e','r','t','y','u','i','o','p','Y','x','c','v','b','Y','b','n','m','Y','q','a','d','Y',]

my goal would be to select in a smart way only the values that are within the last X and the first Y (notice capital X and Y).

The output should be something like this:

vect_f = ['q','w','e','r','t','y','u','i','o','p','Y','x','c','v','b']

Is there a smart way to do this selection. I have figured out a way to do it by counting the number of Xs and Ys and collect only what is comprehended between the corresponding indexes but this is very bad coding in my opinion.

Could you suggest me a nice way to achieve my goal?

Answer Source

One line:

vect_i[(vect_i.reverse(), len(vect_i) - vect_i.index('X'), vect_i.reverse())[1] : vect_i.index('Y')]


vect_i[len(vect_i) - vect_i[::-1].index('X') : vect_i.index('Y')]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download