Posts

Showing posts from June, 2019

for loop and slice

for statement iterates on any discrete sequence of items – as in Java. The syntax is simple: f or <variable > in <sequence> :     <statement> Eg.: words = [ ' this ' , ' that ' , ' another ' ] for w in words:      print (w, len(w)) Side-note here –       for w in words[:]: print (w)    has the same effect as      print (words) You can update a list within the for loop – unlike Java. for w in words:      if len(w) > 6 :           words. remove (w) But, better use a slice to end up with the expected effect in some cases. For instance, the following is an infinite for-loop: for w in words:      if len(w) > 6 :           print (w, ' here is one' )           words.insert( 0 , w)      else : print (w, ' nope' ) This is because, it keeps iterating on the current list – the list that keeps