Home > Blockchain >  Print values that fall between two values in python list
Print values that fall between two values in python list

Time:08-21

The following is a list of names:

names = ["James","Robert","John","Michael","David","William","Richard","Joseph","Thomas","Charles","Christopher","Daniel","Matthew","Anthony","Mark","Donald","Steven","Paul","Andrew","Joshua","Kenneth","Kevin","Brian","George","Timothy","Mary","Patricia","Jennifer","Linda","Elizabeth","Emma","Nicole","Helen","Samantha",...,"Charlotte","Marie","Kayla","Alexis","Lori"]

a = "Emma"
b = "Kayla"

Once Emma and Kayla both are found, how to print all values between Emma and Kayla?

Expected output:

Nicole
Helen
Samantha
...
Charlotte
Marie

CodePudding user response:

One way is to use index() to find a and b, and then just take the slice between them:

>>> names[names.index(a) 1:names.index(b)]
['Nicole', 'Helen', 'Samantha', Ellipsis, 'Charlotte', 'Marie']
>>> print(*names[names.index(a) 1:names.index(b)], sep='\n')
Nicole
Helen
Samantha
Ellipsis
Charlotte
Marie

If you wanted to do it without using index() or the equivalent, this would be a more state-machine-ish implementation with a simple for loop and a flag to track which part of the list you're in:

>>> found_a = False
>>> for n in names:
...     if n == a:
...         found_a = True
...     elif n == b:
...         break
...     elif found_a:
...         print(n)
...
Nicole
Helen
Samantha
Ellipsis
Charlotte
Marie

CodePudding user response:

Assumption used: a and b are distinct names in the list.

self-explanatory code:

flag=False
i=0
while i<len(names)-1:
    if names[i]==a or names[i]==b:
        flag=not flag
    if flag and names[i]!=a and names[i]!=b:
        print(names[i]) 
    i =1

CodePudding user response:

First assumption: a, b are distinct values

Simple and very linear :

bool_variable = False
for name in names:
    if name==a:
        bool_variable = True
        continue
    elif name==b:
        break
    if bool_variable:
        print(name)

Standard:

print(names[names.index(a) 1:names.index(b)])

Happy coding ..!

  • Related