Looping for as a looping parameter while

Asked

Viewed 63 times

1

Whereas the list cont would have the values:

cont = ['t','f','f','t','f']

It would be possible something like this:

while(for cont in cont == 'f'):
    pass

2 answers

2

Yes, but try without the while:

for letraF in [letra for letra in cont if letra == 'f']:
    print(letraF)
  • interesting however the compiler’s answer is SyntaxError: invalid synta

  • @Nasca Sorry. Lack of attention. See the new version.

  • 1

    One suggestion is to use parentheses instead of brackets in the expression that generates the capability of for: this way, Python will generate one element at a time as it is consumed. With brackets it will execute the whole for before, store everything in memory, and run the forexternal after. In practice, for small lists, and synchronous operations, it doesn’t make much difference. For larger sequences, possibly asynchronously generated, this already changes.

  • @jsbueno Yes. Generating expressions are very cool. : ) list comprehensions even because it would be easier to explain in case of clarification request, and because optimizations of this format usually pay even when the data set is large, as you said.

1


You can place a condition when iterating:

letras = ['t','f','f','t','f']

for letra in [i for i in letras if i != 'f']:
    print(letra)

Ver Demonstração

Or put the condition outside the loop:

letras = ['t','f','f','t','f']

for letra in letras:
    if letra == 'f':
        continue
    print(letra)

Ver demonstração

Browser other questions tagged

You are not signed in. Login or sign up in order to post.