# Printing the next element if the previous element is in a list [closed]

I would like to reduce the following Python code. I have one list and a few if statements.

a=[one, two, three, four]

if a[0] in b:
print(a[1])
if a[1] in b:
print(a[2])
if a[2] in b:
print(a[3])
if a[3] in b:
print(a[0])


How can I reduce this to two lines of code and still to run in sequence? It will permit list a to be of "n" length and I will not have to add them individually.

• This does not have enough context to be on topic. What are you actually trying to do with your application? Can you show your whole program? – Reinderien Jun 28 at 1:04
• print([a[(i+1)%len(a)] for i in range(len(a)) if a[i] in b]) – impopularGuy Jun 28 at 5:45

Firstly we can simply loop through a to get the values to check that are in b. However we need to know the index so we can increment a value, i, whilst looping through a.

i = 0
for value in a:
if value in b:
print(a[i + 1])
i += 1


You should notice that this doesn't actually work. This is because on the last value of a we go out of bounds. To fix this we can simply use the modulo operator, %, to keep the value in bounds.

i = 0
for value in a:
if value in b:
print(a[(i + 1) % len(a)])
i += 1


From here we can use enumerate rather than increment i manually. And we start i at 1 to remove the need for that (i + 1).

for i, value in enumerate(a, start=1):
if value in b:
print(a[i % len(a)])


From you have a couple of options.

• You can use zip with itertools to remove the need for i % len(a). This isn't going to be nice to read but can be more performant.
• Use a comprehension to reduce this to one line of code.

However these are more advanced topics.

• Thank you. But how can I do this in sequence? For example with a top "if" and keyboard confirmation. Press enter show first item then another enter the second etc? – Andy Andy Jun 28 at 11:13
• @AndyAndy You have not coded that and so asking for that is off-topic and I will not answer. If you manage to do that by yourself then you can post a new question. – Peilonrayz Jun 28 at 11:15