difference between word: and word[:] in for loop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: difference between word: and word[:] in for loop (/thread-8672.html) |
difference between word: and word[:] in for loop - zowhair - Mar-03-2018 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[:]:?? RE: difference between word: and word[:] in for loop - metulburr - Mar-03-2018 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. RE: difference between word: and word[:] in for loop - zowhair - Mar-03-2018 got it...!! Thanks Dear!! |