0

I wanted to understand why the below 2 statement are treated differently in python.

for w in words:

and

for w in words[ : ]

Here is case where I found both the statement getting a different result. Consider the below code snippet :

words = ['cat', 'window', 'defenestrate']
counter = 0
for w in words:  
    if len(w) > 6:
       words.insert(0, w)
print(words)

in the above snippet , if i use the way it shows, the program goes in a indefinite loop, where as, if i use for w in words[ : ]:, the program exits properly with output :

['defenestrate', 'cat', 'window', 'defenestrate']

I was expecting both to produce similar results

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Side-note: No one leaves [spaces in implicit parts of the slice notation](https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements). It's just `words[:]`. – ShadowRanger Sep 04 '16 at 14:36

1 Answers1

0

Fast answer

for w in words: # perates on actual object

for w in words[ : ] #operates on copy coz "[:]" is slicing whole array
Take_Care_
  • 1,957
  • 1
  • 22
  • 24