0

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"]
erondem
  • 482
  • 1
  • 11
  • 24
  • Is it guaranteed that the list has an even number of elements and it alternates between ok/nope and value? – user202729 Aug 16 '19 at 12:00
  • nope it is not guarenteed. What guarenteed is item always comes after ok/nope . Let me edit question. – erondem Aug 16 '19 at 12:05
  • 1
    Possible duplicate of [Iterate a list as pair (current, next) in Python](https://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python) – user202729 Aug 16 '19 at 12:07

3 Answers3

1
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.

MurrayW
  • 393
  • 2
  • 10
0

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0
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.

Jainil Patel
  • 1,284
  • 7
  • 16