erondem
erondem

Reputation: 582

How to make two iteration in for loop using for-in syntax

Assume I have a list and I am looping in it with for-in syntax. Can this be done with for-in syntax or better question would be what is the most pythonic way to do this?

l= ["ok", "item1", "nope", "item2", "nope", "item3", "ok", "item4"]
for item in l:
    if item == "ok":
        print(item + ": " + ... ) # Where ... should be next item

I want this code prints out something like

ok: item1
ok: item4

edit: A more clear list example would be like accourding to comments:

l= ["ok", "item1", "nope", "item2", "somevalue","nope", "item3", "ok", "item4"]

Upvotes: 0

Views: 122

Answers (3)

Jainil Patel
Jainil Patel

Reputation: 1324

l= ["ok", "item1", "nope", "item2", "nope", "item3", "ok", "item4"]
for itemno in range(len(l)):
    if l[itemno] == "ok":
        print(l[itemno] + ": " +l[itemno+1] ) 

i think no need to use zip or enumerate as they take some computations. so to making problem simple, just think simple.

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

One possibility is use zip() method and slicing:

l= ["nope", "ok", "item1", "nope", "item2", "somevalue","nope", "item3", "ok", "item4"]

for val1, val2 in zip(l[::1], l[1::1]):
    if val1 == 'ok':
        print('{} : {}'.format(val1, val2))

Prints:

ok : item1
ok : item4

Upvotes: 0

MurrayW
MurrayW

Reputation: 393

l= ["ok", "item1", "nope", "item2", "nope", "item3", "ok", "item4"]
for index, item in enumerate(l):
    if item == "ok":
        print(f"{item}: {l[index + 1]}")

using enumerate() you can get the value and the index of the current item from your list. If the value of the current item == "ok", then print the next item from the list via index + 1.

Upvotes: 1

Related Questions