Python Forum

Full Version: difference between word: and word[:] in for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Friends, I have some confusion in python kindly help me. What is difference between these two statements
 
word = ['xyz', 'dsddf', 'sdfs'] 
for w in word:
    if len(w) > 3:
       word.insert(0, w)
and
word = ['xyz', 'dsddf', 'sdfs']
for w in word:
  if len(w) > 3:
      word.insert(0, w) 

 
for w in word: 
VS
for w in word[:]:
??
It is called slicing. Without any numbers however it just returns a shallow copy of the object instead. So you are looping a shallow copy of the object word instead of actual object word.

You should always loop over a copy of the object if you are modifying that object in that same loop. Other wise you can have problems. If you have nested lists inside your list..then you will need a deep copy.
got it...!!
Thanks Dear!!